package com.ocom.payhandle.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.google.gson.Gson;
import com.ocom.common.AcpService;
import com.ocom.common.HttpUtils;
import com.ocom.common.constant.PayHandleUrl;
import com.ocom.common.entity.access.EntityDeptInfo;
import com.ocom.common.entity.card.*;
import com.ocom.common.entity.company.EntityCompanyInfo;
import com.ocom.common.entity.human.EntityPersonnelInfo;
import com.ocom.common.entity.payconfig.EntityXfDeviceMealConfig;
import com.ocom.common.enums.*;
import com.ocom.common.request.exposeapi.abc.ABCConfirmTraceRequest;
import com.ocom.common.request.payconfig.mealorder.RefundOrderDishesRequest;
import com.ocom.common.request.payhandle.*;
import com.ocom.common.resp.Result;
import com.ocom.common.utils.*;
import com.ocom.common.vo.pyhandle.AnalyzeBankUsersVo;
import com.ocom.payhandle.feign.ExposeFeign;
import com.ocom.payhandle.feign.PayConfigClientService;
import com.ocom.payhandle.feign.UgcapiFeign;
import com.ocom.payhandle.feign.XfRecordFeign;
import com.ocom.payhandle.fun.PayFunService;
import com.ocom.payhandle.fun.PayHandleFunService;
import com.ocom.payhandle.mq.business.saveorder.SaveOrderProductService;
import com.ocom.payhandle.service.*;
import com.ocom.payhandle.vo.DeviceInfoVo;
import com.ocom.payhandle.vo.MqSaveOrderVo;
import com.ocom.redis.util.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.*;
import java.util.stream.Collectors;

@RefreshScope
@Slf4j
@RestController
public class PayController {

    @Autowired
    DeviceInfoService deviceInfoService;

    @Autowired
    XfPointInfoService xfPointInfoService;

    @Autowired
    XfChannelInfoService xfChannelInfoService;

    @Autowired
    private XfMealTimeService xfMealTimeService;

    @Autowired
    private XfRecordProcessService xfRecordProcessService;

    @Autowired
    private XfRecordWaitpayService xfRecordWaitpayService;

    @Resource
    private RedisUtil redisUtil;

    @Autowired
    private XfMerchantInfoService xfMerchantInfoService;

//    @Value("${pay.url}")
//    private String payUrl1;

    @Autowired
    private XfRecordFeign xfRecordFeign;

    @Autowired
    private UgcapiFeign ugcapiFeign;

    @Autowired
    private XfCardInfoService xfCardInfoService;

    @Autowired
    private XfAccountInfoService xfAccountInfoService;

    @Autowired
    private PersonnelInfoService personnelInfoService;

    @Autowired
    private DeptInfoService deptInfoService;

    @Autowired
    private XfDiscountConfigServcie xfDiscountConfigServcie;

    @Autowired
    private XfMerchPayInfoService xfMerchPayInfoService;

    @Autowired
    private XfSignNoService xfSignNoService;

    @Autowired
    private ConsTypeConfigService consTypeConfigService;

    @Autowired
    private XfDeviceMealConfigServcie xfDeviceMealConfigServcie;

    @Autowired
    private XfGoodsListProcessService xfGoodsListProcessService;

    @Autowired
    private XfAccountTypeService xfAccountTypeService;

    @Autowired
    PayHandleFunService payHandleFunService;

    @Autowired
    PayFunService payFunService;

    @Autowired
    private ExposeFeign exposeFeign;

    @Autowired
    private SaveOrderProductService saveOrderProductService;

    @Autowired
    private CompanyInfoService companyInfoService;

    @Autowired
    private PayConfigClientService payConfigClientService;


    /**
     * 2.8.1 付款码支付请求（qrCodePay）
     *
     * @param request
     * @return
     */
    @PostMapping(PayHandleUrl.URL_PayHandle_qrCodePay)
    public Result qrCodePay(@RequestBody QrCodePayRequest request) {

        String machno = "";
        String tradeNo = "";
        try {
            machno = request.getMachNo();
            Long companyID = request.getCompanyId();
            //向redis分布式锁插入订单号是否重复
            tradeNo = request.getTradeNo();
            String tradeNoRedis = "onlinePay:" + companyID + ":" + machno + ":" + tradeNo;
            if (redisUtil.lock(tradeNoRedis, 60 * 60)) {
                EntityXfRecordProcess entityXfRecordProcess = new EntityXfRecordProcess();
                String payCodeType = AcpService.thirdtyp(request.getAuthCode());
                entityXfRecordProcess.setOpTypeDiff(Long.valueOf(payCode(payCodeType)));
                entityXfRecordProcess.setConsType(request.getConsType());
                //判断消费时间段
                Date date = new Date();
                entityXfRecordProcess.setCreateTime(date);
                entityXfRecordProcess.setMonthValue(DateUtils.getStrDate(date, "yyyyMM"));
                //查询收费的和商家信息
                relatedDevice(entityXfRecordProcess, request.getCompanyId(), request.getMachNo(), date);
                entityXfRecordProcess.setMealDate(DateUtils.getDate(DateUtils.getStrDate(date, DateUtils.YYYY_MM_DD), DateUtils.YYYY_MM_DD));
                //计算金额
                int consMoney = -request.getAmount();
                entityXfRecordProcess.setConsMoney(Long.valueOf(consMoney));
                int discount = 0;
                int realMoney = consMoney + discount;
                //支付状态；0支付中、1支付成功，2支付失败，3撤单中，4已撤单，5退款中，6已退款，7部分退款成功
                entityXfRecordProcess.setPayState(0);
                entityXfRecordProcess.setDiscount(Long.valueOf(discount));
                entityXfRecordProcess.setRealMoney(Long.valueOf(realMoney));
                entityXfRecordProcess.setPayAmount(Long.valueOf(Math.abs(realMoney)));
                //消费状态，1：消费；2：退款；3：点餐；4.取餐；5.订餐；6：退订；10：充值；11：提现；12：补贴；13：清卡；21：销户
                entityXfRecordProcess.setConsState(request.getConsState());
                //社保码
                if(request.getAuthCode().startsWith("SB")){
                    entityXfRecordProcess.setOpTypeDiff(208l);
                }
                //操作类型：
                //1：虚拟账户支付
                //2：付款码支付
                //3：免密代扣支付
                //4：充值
                //5：补贴
                //6：订餐
                //7：取款
                //8：点菜（具体操作方式为101--305）

                entityXfRecordProcess.setOpType(2L);
                entityXfRecordProcess.setOrderNo(request.getTradeNo());
                try {
                    if (request.getConsState() == 3 || request.getConsState() == 5) {
                        payHandleFunService.relatedReceiptNo(entityXfRecordProcess);
                        if (request.getConsState() == 5) {
                            payHandleFunService.relatedDingCan(entityXfRecordProcess, request.getConsDate(), request.getConsMeal(), request.getConsPoint());
                        }
                    }
                    int i = xfRecordProcessService.insertEntityXfRecord(companyID, entityXfRecordProcess);
                    if (i <= 0) {
                        log.info("请求方式1:【{}】,机器号:【{}】,请求参数:【{}】,返回:【{}】", "支付请求（强在线）", machno, request, ResultUtil.error(ResultEnum.Err_802));
                        //订单号重复
                        return ResultUtil.error(ResultEnum.Err_802);
                    }
                } catch (Exception e) {
                    StackTraceElement ste = e.getStackTrace()[0];
                    log.info("请求方式2:【{}】,机器号:【{}】,入库新增等待表的数据1:【{}】,异常的返回:【{}】,行号:【{}】", "支付请求（强在线）", machno, entityXfRecordProcess, e, ste.getLineNumber());
                    log.info("请求方式3:【{}】,机器号:【{}】,请求参数:【{}】,返回:【{}】", "支付请求（强在线）", machno, request, ResultUtil.error(ResultEnum.Err_802));
                    //订单号重复
                    return ResultUtil.error(ResultEnum.Err_802);
                }
                try {
                    if (request.getConsState() == 3 || request.getConsState() == 5) {
                        xfGoodsListProcessService.saveXfGoodsList(companyID, entityXfRecordProcess, request.getMealData());
                    }
                } catch (Exception e) {
                    StackTraceElement ste = e.getStackTrace()[0];
                    log.info("请求方式4:【{}】,机器号:【{}】,入库新增菜品缓存表数据的数据:【{}】,异常的返回:【{}】,行号:【{}】", "支付请求（强在线）", machno, entityXfRecordProcess, e, ste.getLineNumber());
                }
                //查询配置信息向统一平台发起支付
                EntiyXfMerchPayInfo entiyXfMerchPayInfo = configure(entityXfRecordProcess);

                if (entiyXfMerchPayInfo == null) {
                    //商户支付渠道未配置"
                    return ResultUtil.error(ResultEnum.Err_3048);
                }

                Map<String, Object> retMap = new HashMap<>();
                retMap.put("company_id", entiyXfMerchPayInfo.getCompanyId());
                retMap.put("user_name", entiyXfMerchPayInfo.getUserName());
                retMap.put("password", entiyXfMerchPayInfo.getPassword());
                retMap.put("pos_no", machno);
                retMap.put("fee_type", "CNY");
                retMap.put("subject", "扫付款码支付:" + machno);
                retMap.put("out_trade_no", request.getTradeNo());
                retMap.put("auth_code", request.getAuthCode());
                retMap.put("total_amount", String.valueOf(Math.abs(realMoney)));
                retMap.put("devsnip", String.valueOf("10.68.132.244"));
                retMap.put("body", "扫付款码支付");
                if(request.getAuthCode().startsWith("SB")){
                    retMap.put("pay_channel", "31");
                }
                //向统一支付平台发起支付
                String payUrl = companyInfoService.getPayCenterUrl(companyID, entiyXfMerchPayInfo.getCompanyId());
                String json = HttpUtils.postJson(payUrl + "/unifiedmicropay/nobeswept.do", retMap);
                JSONObject results = JSON.parseObject(json);
//                EntityXfRecordProcess updateXfRecordProcess = new EntityXfRecordProcess();
//                updateXfRecordProcess.setId(entityXfRecordProcess.getId());
                entityXfRecordProcess.setPayChannelNo(entiyXfMerchPayInfo.getCompanyId());
                if (results.getInteger("code") == 200) {
                    Map<String, String> dataMap = (Map<String, String>) JSON.parse(results.getString("data"));
                    //支付成功，修改等待表的状态和把数据入成功表
                    entityXfRecordProcess.setChannelOrderNo(dataMap.get("trade_no"));
                    entityXfRecordProcess.setPayState(1);
                    entityXfRecordProcess.setPayWay(PayWar.getPayWar(dataMap.get("trade_type")));
                    entityXfRecordProcess.setOpTypeDiff(Long.valueOf(payCode(dataMap.get("pay_code_type"))));
                    entityXfRecordProcess.setPayTime(DateUtil.getDate(dataMap.get("time_end"), "yyyyMMddHHmmss"));
                    if (entityXfRecordProcess.getPayWay() == 31) {
                        JSONObject jsonObject = JSON.parseObject(dataMap.get("body"));
                        entityXfRecordProcess.setPCode(jsonObject.getString("idNo"));
                        entityXfRecordProcess.setPName(jsonObject.getString("userName"));
                        Integer realMoneyUse = Integer.valueOf(dataMap.get("total_amount")) * -1;
                        entityXfRecordProcess.setRealMoney(realMoneyUse.longValue());
                        entityXfRecordProcess.setPCode(jsonObject.getString("idNo"));
                        entityXfRecordProcess.setPName(jsonObject.getString("userName"));
                        entityXfRecordProcess.setRealMoney(realMoneyUse.longValue());
                    }
                    entityXfRecordProcess.setPayChannelNo(entiyXfMerchPayInfo.getCompanyId());
                    try {
                        int i = xfRecordProcessService.updateEntityXfRecord(companyID, entityXfRecordProcess);
                        if (i <= 0) {
                            log.info("请求方式5:【{}】,机器号:【{}】,入库修改的数据:【{}】,返回:【{}】", "支付请求（强在线）", machno, entityXfRecordProcess, "等待表修改入库失败");
                            log.info("请求方式6:【{}】,机器号:【{}】,统一支付平台的请求参数:【{}】,统一支付平台的返回:【{}】", "支付请求（强在线）", machno, retMap, json);

                        }
                    } catch (Exception e) {
                        StackTraceElement ste = e.getStackTrace()[0];
                        log.info("请求方式7:【{}】,机器号:【{}】,入库修改的数据:【{}】,异常的返回:【{}】,行号:【{}】", "支付请求（强在线）", machno, entityXfRecordProcess, e, ste.getLineNumber());
                        log.info("请求方式8:【{}】,机器号:【{}】,统一支付平台的请求参数:【{}】,统一支付平台的返回:【{}】", "支付请求（强在线）", machno, retMap, json);
                    }
//					entiyEntiyXfRecordProcess.setId(null);
                    entityXfRecordProcess.setChannelOrderNo(dataMap.get("trade_no"));
                    entityXfRecordProcess.setPayState(1);
                    if (!dataMap.get("trade_type").equals("")) {
                        entityXfRecordProcess.setPayWay(PayWar.getPayWar(dataMap.get("trade_type")));
                    }
                    if (!dataMap.get("pay_code_type").equals("")) {
                        entityXfRecordProcess.setOpTypeDiff(Long.valueOf(payCode(dataMap.get("pay_code_type"))));
                    }

                    try {

                        String redOrdKey = "redisOrder:" + entityXfRecordProcess.getComId()+":"
                        		+entityXfRecordProcess.getOrderNo();

                        String toJson = JsonUtils.toJson(entityXfRecordProcess);
                        redisUtil.set(redOrdKey,toJson,500l);

                        MqSaveOrderVo mqSaveOrderVo = new MqSaveOrderVo();
                        mqSaveOrderVo.setComId(request.getCompanyId());
                        mqSaveOrderVo.setId(entityXfRecordProcess.getId());
                        mqSaveOrderVo.setMachNo(entityXfRecordProcess.getDeviceNo());
                        mqSaveOrderVo.setRedisOrderNo(redOrdKey);
                        saveOrderProductService.saveOrder(mqSaveOrderVo);
                    } catch (Exception e) {
                        StackTraceElement ste = e.getStackTrace()[0];
                        log.info("请求方式9:【{}】,机器号:【{}】,被扫-入库新增菜品缓存表数据的数据:【{}】,异常的返回:【{}】,行号:【{}】", "支付请求（强在线）", machno, entityXfRecordProcess, e, ste.getLineNumber());
                    }
                    Map<String, Object> map = new HashMap<>();
                    map.put("discount", entityXfRecordProcess.getDiscount());
                    map.put("payAmount", entityXfRecordProcess.getRealMoney());
                    map.put("pickupNum", entityXfRecordProcess.getReceiptNo());
                    map.put("orderTime", DateUtil.getDateTime(entityXfRecordProcess.getPayTime()));
                    map.put("opTypeDiff", entityXfRecordProcess.getOpTypeDiff());
                    return ResultUtil.success(map);
                } else if (results.getInteger("code") == 16 || results.getInteger("code") == 19
                        || results.getInteger("code") == 7 || json.contains("Exception")) {
                    //支付结果未知
                    return ResultUtil.error(ResultEnum.Err_3029);
                }
                log.info("请求方式10:【{}】,机器号:【{}】,返回的参数:【{}】", "支付请求（强在线）", machno, ResultUtil.error(ResultEnum.Err_3030));
                log.info("请求方式11:【{}】,机器号:【{}】,统一支付平台的请求参数:【{}】,统一支付平台的返回:【{}】", "支付请求（强在线）", machno, retMap, json);
                entityXfRecordProcess.setPayState(2);
                try {
                    int i = xfRecordProcessService.updateEntityXfRecord(companyID, entityXfRecordProcess);
                    if (i <= 0) {
                        log.info("请求方式12:【{}】,机器号:【{}】,入库修改的数据:【{}】,返回:【{}】", "支付请求（强在线）", machno, entityXfRecordProcess, "等待表修改入库失败");
                        log.info("请求方式13:【{}】,机器号:【{}】,统一支付平台的请求参数:【{}】,统一支付平台的返回:【{}】", "支付请求（强在线）", machno, retMap, json);

                    }
                } catch (Exception e) {
                    StackTraceElement ste = e.getStackTrace()[0];
                    log.info("请求方式14:【{}】,机器号:【{}】,入库修改的数据:【{}】,异常的返回:【{}】,行号:【{}】", "支付请求（强在线）", machno, entityXfRecordProcess, e, ste.getLineNumber());
                    log.info("请求方式15:【{}】,机器号:【{}】,统一支付平台的请求参数:【{}】,统一支付平台的返回:【{}】", "支付请求（强在线）", machno, retMap, json);
                }
                return ResultUtil.error(ResultEnum.Err_3030);
            } else {
                log.info("请求方式16:【{}】,机器号:【{}】,请求参数:【{}】,返回:【{}】", "支付请求（强在线）", machno, request, ResultUtil.error(ResultEnum.Err_802));
                //订单号重复
                return ResultUtil.error(ResultEnum.Err_802);
            }
        } catch (Exception e) {
            StackTraceElement ste = e.getStackTrace()[0];
            log.info("请求方式17:【{}】,机器号:【{}】,请求参数:【{}】,异常1:【{}】,行号:【{}】", "支付请求（强在线）", machno, request, e, ste.getLineNumber());
            return ResultUtil.error(ResultEnum.Err_3031);
        }
    }

    /**
     * 2.8.2 付款码订单查询（qrCodeQuery）
     *
     * @param request
     * @return
     */
    @PostMapping(PayHandleUrl.URL_PayHandle_qrCodeQuery)
    public Result qrCodeQuery(@Valid @RequestBody QrCodeQueryRequest request) {
        return payFunService.qrCodeQuery(request);
    }

    /*
     * @Description:在线订单查询
     * @Author: lu
     * @Date: 2022/7/7 16:05
     * @param request:
     * @return: com.ocom.common.resp.Result
     **/
    @PostMapping(PayHandleUrl.URL_OnlinePayQuery)
    public Result onlinePayQuery(@Valid @RequestBody QrCodeQueryRequest request) {
        try {
            EntityXfRecordProcess entityXfRecordProcess = xfRecordProcessService.selectTradeNo(request.getCompanyId(), request.getTradeNo(), request.getMachNo());

            if (entityXfRecordProcess == null) {
                return ResultUtil.error(ResultEnum.Err_1001);
            }

            //补缴单
            if(!CommonUtil.isNull(entityXfRecordProcess.getPlatOrderNo()) && !CommonUtil.isNull(entityXfRecordProcess.getOrigOrderNo())){
                //补缴单查询返回成功
                Map<String, Object> map = new HashMap<>();
                map.put("discount", entityXfRecordProcess.getDiscount());
                map.put("payAmount", entityXfRecordProcess.getRealMoney());
                map.put("pickupNum", entityXfRecordProcess.getReceiptNo());
                map.put("orderTime", DateUtil.getDateTime(entityXfRecordProcess.getPayTime()));
                return ResultUtil.success(map);
            }

            if (entityXfRecordProcess.getPayState() == 1) {
                //成功
                Map<String, Object> map = new HashMap<>();
                map.put("discount", entityXfRecordProcess.getDiscount());
                map.put("payAmount", entityXfRecordProcess.getRealMoney());
                Map<String, Object> mapAccountInf = new HashMap<>();
                mapAccountInf.put("name", entityXfRecordProcess.getPName());
                mapAccountInf.put("money", entityXfRecordProcess.getChargeBalance());
                mapAccountInf.put("allowance", entityXfRecordProcess.getSubMoney());
                mapAccountInf.put("cardtype", entityXfRecordProcess.getSubBalance());
                map.put("accountInf", mapAccountInf);
                map.put("pickupNum", entityXfRecordProcess.getReceiptNo());
                map.put("orderTime", DateUtil.getDateTime(entityXfRecordProcess.getPayTime()));
                return ResultUtil.success(map);
            } else if (entityXfRecordProcess.getPayState() == 3 || entityXfRecordProcess.getPayState() == 4) {
                //已撤单
                return ResultUtil.error(ResultEnum.Err_3033);
            } else {
                if (entityXfRecordProcess.getOpTypeDiff() > 200l) {
                    return payFunService.qrCodeQuery(request);
                }
                //支付结果未知
                return ResultUtil.error(ResultEnum.Err_3029);
            }
        } catch (Exception e) {
            StackTraceElement ste = e.getStackTrace()[0];
            log.info("请求方式18:【{}】,机器号:【{}】,请求参数:【{}】,异常:【{}】,行号:【{}】", "刷卡订单查询", request.getMachNo(), request, e, ste.getLineNumber());
            return ResultUtil.error(ResultEnum.Err_3031);
        }
    }

    /**
     * 2.8.3 付款码撤单（qrCodeCancel）
     *
     * @param request
     * @return
     */
    @PostMapping(PayHandleUrl.URL_PayHandle_qrCodeCancel)
    public Result qrCodeCancel(@Valid @RequestBody QrCodeQueryRequest request) {
        String machno = "";
        try {
            machno = request.getMachNo();
            Long companyID = request.getCompanyId();
            //查看数据库次订单是否支付成功
            EntityXfRecordProcess entityXfRecordProcess = xfRecordProcessService.selectTradeNo(companyID, request.getTradeNo(), request.getMachNo());
            if (entityXfRecordProcess == null) {
                //订单号号不存在
                return ResultUtil.error(ResultEnum.Err_805);
            }
            if (entityXfRecordProcess.getPayState() == 4) {
                //已撤单
                return ResultUtil.success();
            }
            //查询配置信息向统一平台发起支付
            EntiyXfMerchPayInfo entiyXfMerchPayInfo = configure(entityXfRecordProcess);

            if (entiyXfMerchPayInfo == null) {
                //商户支付渠道未配置"
                return ResultUtil.error(ResultEnum.Err_3048);
            }
            Map<String, Object> retMap = new HashMap<>();
            retMap.put("company_id", entiyXfMerchPayInfo.getCompanyId());
            retMap.put("user_name", entiyXfMerchPayInfo.getUserName());
            retMap.put("password", entiyXfMerchPayInfo.getPassword());
            retMap.put("pos_no", machno);
            retMap.put("out_trade_no", request.getTradeNo());
            //向统一支付平台发起支付
            String payUrl = companyInfoService.getPayCenterUrl(companyID, entiyXfMerchPayInfo.getCompanyId());
            String json = HttpUtils.postsJson(payUrl + "/unifiedmicropay/cancellations.do", retMap);
            JSONObject results = JSON.parseObject(json);
            if (results.getInteger("code") == 200) {
                EntityXfRecord entityXfRecord = JSON.parseObject(JSON.toJSONString(entityXfRecordProcess), EntityXfRecord.class);
                Result result = xfRecordFeign.deleteXfRecord(entityXfRecord);
                if (result.getCode() != 200) {
                    log.info("请求方式19:【{}】,机器号:【{}】,删除成功表的数据:【{}】,返回:【{}】", "付款码撤单", machno, entityXfRecordProcess, "删除失败");
                    log.info("请求方式20:【{}】,机器号:【{}】,请求参数:【{}】,请求删除成功表的xfrecode的表数据的返回的参数:【{}】", "付款码撤单", machno, retMap, result);
                }
                EntityXfRecordProcess updateXfRecordProcess = new EntityXfRecordProcess();
                updateXfRecordProcess.setId(entityXfRecordProcess.getId());
                updateXfRecordProcess.setPayState(4);
                try {
                    int i = xfRecordProcessService.updateEntityXfRecord(companyID, updateXfRecordProcess);
                    if (i <= 0) {
                        log.info("请求方式21:【{}】,机器号:【{}】,入库修改的数据:【{}】,返回:【{}】", "付款码撤单", machno, updateXfRecordProcess, "等待表修改入库失败");
                        log.info("请求方式22:【{}】,机器号:【{}】,统一支付平台的请求参数:【{}】,统一支付平台的返回:【{}】", "付款码撤单", machno, retMap, json);
                    }
                } catch (Exception e) {
                    StackTraceElement ste = e.getStackTrace()[0];
                    log.info("请求方式23:【{}】,机器号:【{}】,入库修改的数据:【{}】,异常的返回:【{}】,行号:【{}】", "付款码撤单", machno, updateXfRecordProcess, e, ste.getLineNumber());
                    log.info("请求方式24:【{}】,机器号:【{}】,统一支付平台的请求参数:【{}】,统一支付平台的返回:【{}】", "付款码撤单", machno, retMap, json);
                }
                return ResultUtil.success();
            } else {
                EntityXfRecordProcess updateXfRecordProcess = new EntityXfRecordProcess();
                updateXfRecordProcess.setId(entityXfRecordProcess.getId());
                updateXfRecordProcess.setPayState(3);
                try {
                    int i = xfRecordProcessService.updateEntityXfRecord(companyID, updateXfRecordProcess);
                    if (i <= 0) {
                        log.info("请求方式25:【{}】,机器号:【{}】,入库修改的数据:【{}】,返回:【{}】", "付款码撤单", machno, updateXfRecordProcess, "等待表修改入库失败");
                        log.info("请求方式26:【{}】,机器号:【{}】,统一支付平台的请求参数:【{}】,统一支付平台的返回:【{}】", "付款码撤单", machno, retMap, json);
                    }
                } catch (Exception e) {
                    StackTraceElement ste = e.getStackTrace()[0];
                    log.info("请求方式27:【{}】,机器号:【{}】,入库修改的数据:【{}】,异常的返回:【{}】,行号:【{}】", "付款码撤单", machno, updateXfRecordProcess, e, ste.getLineNumber());
                    log.info("请求方式28:【{}】,机器号:【{}】,统一支付平台的请求参数:【{}】,统一支付平台的返回:【{}】", "付款码撤单", machno, retMap, json);
                }
                return ResultUtil.error(ResultEnum.Err_3035);
            }
        } catch (Exception e) {
            StackTraceElement ste = e.getStackTrace()[0];
            log.info("请求方式29:【{}】,机器号:【{}】,请求参数:【{}】,异常:【{}】,行号:【{}】", "付款码撤单", machno, request, e, ste.getLineNumber());
            return ResultUtil.error(ResultEnum.Err_3031);
        }
    }

    /**
     * 2.8.4 付款码退款
     *
     * @param request
     * @return
     */
    @PostMapping(PayHandleUrl.URL_PayHandle_qrCodeRefund)
    public Result qrCodeRefund(@Valid @RequestBody QrCodeRefundRequest request) {
        return payFunService.qrCodeRefund(request);
    }

    /**
     * 2.8.8 退费（feeRefund）
     *
     * @param request
     * @return
     */
    @PostMapping(PayHandleUrl.URL_PayHandle_feeRefund)
    public Result feeRefund(@Valid @RequestBody FeeRefundRequest request) {
        try {
            //查询订单号是否存在
            EntityXfRecordProcess entityXfRecordProcess = xfRecordProcessService.selectTradeNo(request.getCompanyId(), request.getOrigTradeNo(), null);
            if (entityXfRecordProcess == null) {
                //原订单号不存在
                return ResultUtil.error(ResultEnum.Err_3036);
            }
            Integer consState = entityXfRecordProcess.getConsState();
            request.setOrigTradeNo(entityXfRecordProcess.getOrderNo());
            if (entityXfRecordProcess.getIfRefund() > 0) {
                //
                return ResultUtil.error(ResultEnum.Err_3038);
            }
            Long totalAmount = entityXfRecordProcess.getRealMoney();
            Long id = entityXfRecordProcess.getId();
            Long ifRefund = entityXfRecordProcess.getIfRefund();
            String monthValue = entityXfRecordProcess.getMonthValue();

            String tradeNoRedis = "refund:" + request.getCompanyId() + ":" + request.getTradeNo();
            if (!redisUtil.lock(tradeNoRedis, 60 * 60)) {
                //订单号重复
                return ResultUtil.error(ResultEnum.Err_802);
            }
            if (entityXfRecordProcess.getPayState() != 1 || (entityXfRecordProcess.getConsState() != 1 && entityXfRecordProcess.getConsState() != 3 && entityXfRecordProcess.getConsState() != 5 && entityXfRecordProcess.getConsState() != 111)) {
                return ResultUtil.error(ResultEnum.Err_3037);
            }
            EntityXfRecordProcess refundXfRecordProcess = xfRecordProcessService.selectTradeNo(request.getCompanyId(), request.getTradeNo(), null);


            if (refundXfRecordProcess != null) {
                if (!refundXfRecordProcess.getOrigOrderNo().equals(request.getOrigTradeNo())) {
                    //订单号重复
                    return ResultUtil.error(ResultEnum.Err_802);
                }
                if (entityXfRecordProcess.getIfRefund() > 0) {
                    //退款成功
                    Map<String, Object> map = new HashMap<>();
                    map.put("refundAmount", request.getRefundAmount());
                    return ResultUtil.success(map);
                }
                if (refundXfRecordProcess.getPayState() == 1) {
                    Map<String, Object> map = new HashMap<>();
                    map.put("refundAmount", request.getRefundAmount());
                    return ResultUtil.success(map);
                }
            }


            entityXfRecordProcess.setId(null);
            Date date = new Date();
            entityXfRecordProcess.setCreateTime(date);
            entityXfRecordProcess.setConsTime(date);
            if (Math.abs(entityXfRecordProcess.getRealMoney()) < request.getRefundAmount()) {
                //退款金额超过原订单支付金额
                return ResultUtil.error(ResultEnum.Err_3038);
            }
            entityXfRecordProcess.setConsMoney(Long.valueOf(request.getRefundAmount()));
            entityXfRecordProcess.setDiscount(0l);
            entityXfRecordProcess.setRealMoney(Long.valueOf(request.getRefundAmount()));
            entityXfRecordProcess.setConsState(2);
            entityXfRecordProcess.setOrigOrderNo(request.getOrigTradeNo());
            entityXfRecordProcess.setOrderNo(request.getTradeNo());
            entityXfRecordProcess.setPayState(0);
            entityXfRecordProcess.setOrderNo(request.getTradeNo());
            entityXfRecordProcess.setIfRefund(0l);
            entityXfRecordProcess.setMonthValue(DateUtils.getStrDate(date, "yyyyMM"));
            entityXfRecordProcess.setPayAmount(-Long.valueOf(request.getRefundAmount()));
            try {
                int i = xfRecordProcessService.insertEntityXfRecord(request.getCompanyId(), entityXfRecordProcess);
                if (i <= 0) {
                    log.info("请求方式42:【{}】,机器号:【{}】,请求参数:【{}】,返回:【{}】", "付款码退款", "feeRefund", request, ResultUtil.error(ResultEnum.Err_802));
                    //订单号重复
                    return ResultUtil.error(ResultEnum.Err_802);
                }
            } catch (Exception e) {
                StackTraceElement ste = e.getStackTrace()[0];
                log.info("请求方式43:【{}】,机器号:【{}】,入库新增等待表的数据3:【{}】,异常的返回:【{}】,行号:【{}】", "付款码退款", "feeRefund", entityXfRecordProcess, e, ste.getLineNumber());
                log.info("请求方式44:【{}】,机器号:【{}】,请求参数:【{}】,返回:【{}】", "付款码退款", "feeRefund", request, ResultUtil.error(ResultEnum.Err_802));
                //订单号重复
                return ResultUtil.error(ResultEnum.Err_802);
            }


            //判断是走什么通道的
            //修改等待表的退款数据
            EntityXfRecordProcess updateXfRecordProces = new EntityXfRecordProcess();
            if (entityXfRecordProcess.getOpType() == 2 || entityXfRecordProcess.getOpTypeDiff() >= 200) {
                //查询配置信息向统一平台发起支付
           //     EntiyXfMerchPayInfo entiyXfMerchPayInfo = configure(entityXfRecordProcess);
                EntiyXfMerchPayInfo entiyXfMerchPayInfo = xfMerchPayInfoService.selectConfigure(request.getCompanyId(),entityXfRecordProcess.getPayChannelNo());

                if (entiyXfMerchPayInfo == null) {
                    //商户支付渠道未配置"
                    return ResultUtil.error(ResultEnum.Err_3048);
                }
                Map<String, Object> retMap = new HashMap<>();
                retMap.put("company_id", entiyXfMerchPayInfo.getCompanyId());
                retMap.put("user_name", entiyXfMerchPayInfo.getUserName());
                retMap.put("password", entiyXfMerchPayInfo.getPassword());
                retMap.put("out_trade_no", request.getOrigTradeNo());
                retMap.put("out_refund_no", request.getTradeNo());
                retMap.put("pos_no", null);
                retMap.put("total_amount", Math.abs(totalAmount));
                retMap.put("refund_fee", request.getRefundAmount());
                retMap.put("refund_desc", "退款");
                //向统一支付平台发起支付
                String json = "";
//				if(entiyEntiyXfRecordProcess.getPayWay()==28){
//					json= HttpUtils.postsJson(payUrl+"/withholding/refund.do",retMap);
//				}else{
                String payUrl = companyInfoService.getPayCenterUrl(request.getCompanyId(), entiyXfMerchPayInfo.getCompanyId());
                json = HttpUtils.postsJson(payUrl + "/unifiedmicropay/refund.do", retMap);
//				}
                JSONObject results = JSON.parseObject(json);
                if (results.getInteger("code") != 200) {
                    log.info("请求方式45:【{}】,机器号:【{}】,入库新增的数据:【{}】,返回:【{}】", "付款码退款", "feeRefund", entityXfRecordProcess, "付款码退款失败");
                    log.info("请求方式46:【{}】,机器号:【{}】,统一支付平台的请求参数:【{}】,统一支付平台的返回:【{}】", "付款码退款", "feeRefund", retMap, json);
                    return ResultUtil.error(ResultEnum.Err_3039);
                }
                Map<String, String> dataMap = (Map<String, String>) JSON.parse(results.getString("data"));
                updateXfRecordProces.setPayChannelNo(entiyXfMerchPayInfo.getCompanyId());

                entityXfRecordProcess.setChannelOrderNo(dataMap.get("refund_id"));
                entityXfRecordProcess.setPayAmount(-Long.valueOf(dataMap.get("refund_fee")));

                updateXfRecordProces.setChannelOrderNo(dataMap.get("refund_id"));
                updateXfRecordProces.setPayAmount(-Long.valueOf(dataMap.get("refund_fee")));
            } else if (//entiyEntiyXfRecordProcess.getOpType()==1 &&
                    entityXfRecordProcess.getOpTypeDiff() == 100) {
                //虚拟账户只允许退一次款，不然对于两个钱包都扣款的交易记录不好退款
                if (ifRefund > 0) {
                    return ResultUtil.error(ResultEnum.Err_3038);
                }

                EntityCardInfo entityCardInfo = null;
                if (null != entityXfRecordProcess.getCardNo()) {
                    entityCardInfo = xfCardInfoService.selectCard(request.getCompanyId(), entityXfRecordProcess.getCardNo());
                    if (entityXfRecordProcess.getOpType() == 22 || entityXfRecordProcess.getOpType() == 21) {
                        entityCardInfo = xfCardInfoService.selectCardByPid(request.getCompanyId(), entityXfRecordProcess.getPId());
                    }
                }

//				EntityXfAccountInfo entityXfAccountInfo=xfAccountInfoService.selectAccount(request.getCompanyId(),entityCardInfo.getAccountNo());
                EntityXfAccountInfo entityXfAccountInfo = xfAccountInfoService.selectAccountPid(request.getCompanyId(), entityXfRecordProcess.getPId());
                Long refundAmount = Long.valueOf(Math.abs(request.getRefundAmount()));
                Long chargeBalance = refundAmount + entityXfAccountInfo.getAccountRechargeMoney();
                Long subBalance = Long.valueOf(Math.abs(entityXfRecordProcess.getSubMoney()));
                entityXfRecordProcess.setChargeBalance(chargeBalance);
                updateXfRecordProces.setChargeBalance(chargeBalance);
                if (entityCardInfo != null) {
                    xfCardInfoService.upateCardMoneyA(request.getCompanyId(), entityCardInfo);
                }
                boolean updateAccount = xfAccountInfoService.updateAccountMoney(request.getCompanyId(), Math.abs(entityXfRecordProcess.getChargeMoney()), subBalance, entityXfAccountInfo.getId());
                if (!updateAccount) {
                    return ResultUtil.error(ResultEnum.Err_3039);
                }
                entityXfRecordProcess.setChargeMoney(Math.abs(entityXfRecordProcess.getChargeMoney()));
                entityXfRecordProcess.setSubMoney(subBalance);
            }

            //修改等待表的原订单表的数据
            EntityXfRecordProcess updateXfRecordProcess = new EntityXfRecordProcess();
            updateXfRecordProcess.setId(id);

            updateXfRecordProcess.setRefundTime(new Date());
            updateXfRecordProcess.setIfRefund(ifRefund + 1);
            try {
                int i = xfRecordProcessService.updateEntityXfRecord(request.getCompanyId(), updateXfRecordProcess);
                if (i <= 0) {
                    log.info("请求方式47:【{}】,机器号:【{}】,入库修改的数据:【{}】,返回:【{}】", "付款码退款", "feeRefund", updateXfRecordProcess, "付款码退款失败");
                }
            } catch (Exception e) {
                StackTraceElement ste = e.getStackTrace()[0];
                log.info("请求方式48:【{}】,机器号:【{}】,入库修改的数据:【{}】,异常的返回:【{}】,行号:【{}】", "付款码退款", "feeRefund", updateXfRecordProcess, e, ste.getLineNumber());
            }
            if (consState == 3 || consState == 5) {
                xfGoodsListProcessService.xfGoodsListRrfund(entityXfRecordProcess.getComId(), entityXfRecordProcess.getOrigOrderNo());
            }

            //修改成功表的原订单表的数据
            updateXfRecordProcess.setComId(request.getCompanyId());
            updateXfRecordProcess.setOrderNo(request.getOrigTradeNo());
            updateXfRecordProcess.setMonthValue(monthValue);
//			updateXfRecordProcess.setDeviceNo(request.getMachNo());
            EntityXfRecord entityXfRecord = JSON.parseObject(JSON.toJSONString(updateXfRecordProcess), EntityXfRecord.class);
            Result result = xfRecordFeign.updateXfRecord(entityXfRecord);
            if (result.getCode() != 200) {
                log.info("请求方式49:【{}】,机器号:【{}】,修改成功表的数据:【{}】,返回:【{}】", "付款码退款", "feeRefund", entityXfRecord, "修改原订单信息失败");
            }
            if (consState == 3 || consState == 5) {
                RefundOrderDishesRequest refundOrderDishesRequest = new RefundOrderDishesRequest();
                refundOrderDishesRequest.setComId(entityXfRecordProcess.getComId());
                refundOrderDishesRequest.setOrderNo(request.getOrigTradeNo());
                refundOrderDishesRequest.setMonthValue(entityXfRecordProcess.getMonthValue());
                refundOrderDishesRequest.setRemark("菜品退款");
                xfRecordFeign.refund(refundOrderDishesRequest);
            }

            //新增成功表的退款数据
            Date payTime = new Date();
            entityXfRecordProcess.setPayTime(payTime);
            entityXfRecordProcess.setPayState(1);

            Result sveResult = xfRecordFeign.sveXfRecord(entityXfRecordProcess);
            if (sveResult.getCode() != 200) {
                log.info("请求方式50:【{}】,机器号:【{}】,入库成功的数据:【{}】,返回:【{}】", "付款码退款", "feeRefund", entityXfRecordProcess, "添加入库失败");
            }

            updateXfRecordProces.setId(entityXfRecordProcess.getId());
            updateXfRecordProces.setPayTime(payTime);
            updateXfRecordProces.setPayState(1);

            try {
                int i = xfRecordProcessService.updateEntityXfRecord(request.getCompanyId(), updateXfRecordProces);
                if (i <= 0) {
                    log.info("请求方式51:【{}】,机器号:【{}】,等待表的入库修改的数据:【{}】,返回:【{}】", "付款码退款", "feeRefund", updateXfRecordProcess, "等待表修改入库失败");
                }
            } catch (Exception e) {
                StackTraceElement ste = e.getStackTrace()[0];
                log.info("请求方式52:【{}】,机器号:【{}】,等待表的入库修改的数据:【{}】,异常的返回:【{}】,行号:【{}】", "付款码退款", "feeRefund", updateXfRecordProcess, e, ste.getLineNumber());
            }
            Map<String, Object> map = new HashMap<>();
            map.put("refundAmount", request.getRefundAmount());
            return ResultUtil.success(map);
        } catch (Exception e) {
            e.getStackTrace();
            StackTraceElement ste = e.getStackTrace()[0];
            log.info("请求方式53:【{}】,机器号:【{}】,请求参数:【{}】,异常:【{}】,行号:【{}】", "退款异常", "feeRefund", request, e, ste.getLineNumber());
            return ResultUtil.error(ResultEnum.Err_3031);
        }
    }


    /*
     * @Description:保存消费记录
     * @Author: lu
     * @Date: 2022/7/4 16:32
     * @param request:
     * @return: com.ocom.common.resp.Result
     **/
//    @PostMapping(PayHandleUrl.saveXfRecord)
//    public Result saveXfRecord(@Valid @RequestBody TradeRecordRequest request) {
//        EntityXfRecordProcess entityXfRecordProcess = new EntityXfRecordProcess();
//        String orderNo = "LX" + request.getTradeNo();
//        entityXfRecordProcess.setOrderNo(orderNo);
//        entityXfRecordProcess.setComId(request.getCompanyId());
//        try {
//            String tradeNoRedis = "TradeRecord:" + request.getCompanyId() + ":" + request.getMachNo() + ":" + orderNo;
//            if (!redisUtil.lock(tradeNoRedis, 60 * 60)) {
//                //订单号重复
//                return ResultUtil.success("订单号重复");
//            }
//            Long pId = Long.valueOf(request.getUserId());
//            EntityPersonnelInfo entityPersonnelInfo = personnelInfoService.selectPersonnel(request.getCompanyId(), pId);
//            EntityXfAccountInfo entityXfAccountInfo = xfAccountInfoService.selectAccountPid(request.getCompanyId(), pId);
//            entityXfRecordProcess.setPId(pId);
//            //1-刷卡，4-刷脸， 3-ocom离线码
//            if (request.getType() == 1) {
//                entityXfRecordProcess.setOpType(1l);
//                entityXfRecordProcess.setOpTypeDiff(100l);
//            } else if (request.getType() == 4) {
//                entityXfRecordProcess.setOpType(22l);
//                entityXfRecordProcess.setOpTypeDiff(100l);
//            } else if (request.getType() == 3) {
//                entityXfRecordProcess.setOpType(21l);
//                entityXfRecordProcess.setOpTypeDiff(100l);
//            }
//            String cardNo = "";
//            try {
//                EntityCardInfo entityCardInfo = xfCardInfoService.selectCardByPid(request.getCompanyId(), pId);
//                if (entityCardInfo != null && entityCardInfo.getCardState() < 2) {
//                    cardNo = entityCardInfo.getCardNo();
//                }
//            } catch (Exception e) {
//                log.info("离线记录-查卡号异常 【{}】", e);
//            }
//            entityXfRecordProcess.setCardNo(cardNo);
//
//            entityXfRecordProcess.setAccountNo(entityXfAccountInfo.getAccountNo());
//            //判断是否是异常单
//            if (entityPersonnelInfo == null || entityPersonnelInfo.getStatus() != 0) {
//                entityXfRecordProcess.setPayState(-103);
//            } else {
//                if (entityXfAccountInfo == null || entityXfAccountInfo.getAccountState() != 0) {
//                    entityXfRecordProcess.setPayState(-104);
//                }
//            }
//
//
//            entityXfRecordProcess.setDeviceNo(request.getMachNo());
//            //entiyXfRecordProcess.setCardNo(request.getAuthCode());
//            if (entityPersonnelInfo != null) {
//                entityXfRecordProcess.setPCode(entityPersonnelInfo.getPCode());
//                entityXfRecordProcess.setPName(entityPersonnelInfo.getPName());
//            }
//            if (entityXfAccountInfo != null) {
//                entityXfRecordProcess.setAccountNo(entityXfAccountInfo.getAccountNo());
//                entityXfRecordProcess.setPId(entityXfAccountInfo.getPId());
//            }
//
//            entityXfRecordProcess.setDeptId(entityPersonnelInfo.getDeptId());
//            EntityDeptInfo entityDeptInfo = deptInfoService.selectDeptName(request.getCompanyId(), entityPersonnelInfo.getDeptId());
//            if (entityDeptInfo != null) {
//                entityXfRecordProcess.setDeptName(entityDeptInfo.getDeptName());
//            }
//            //判断消费时间段
//            Date consTime = DateUtils.getDate(request.getTradeTime(), DateUtils.YYYY_MM_DD_HH_MM_SS);
//            Date newDate = new Date();
//            entityXfRecordProcess.setCreateTime(newDate);
//            entityXfRecordProcess.setConsTime(consTime);
//            entityXfRecordProcess.setMonthValue(DateUtils.getStrDate(newDate, "yyyyMM"));
//            //查询收费的和商家信息
//            relatedDevice(entityXfRecordProcess, request.getCompanyId(), request.getMachNo(), consTime);
//            entityXfRecordProcess.setMealDate(DateUtils.getDate(DateUtils.getStrDate(consTime, DateUtils.YYYY_MM_DD), DateUtils.YYYY_MM_DD));
//
//            if (request.getLineSymbol() == 0) {
//                entityXfRecordProcess.setPayState(-101);
//            } else {
//                if (request.getLineSymbol() == 2) {
//                    EntityXfRecordProcess processTradeNo = xfRecordProcessService.selectTradeNo(request.getCompanyId(), request.getTradeNo(), request.getMachNo());
//                    if (processTradeNo != null) {
//                        if (processTradeNo.getPayState() == 1) {
//                            entityXfRecordProcess.setPayState(-102);
//                        }
//                    }
//                }
//            }
//            Integer intMealNo = 0;
//            if (entityXfRecordProcess.getMealNo() != null) {
//                intMealNo = Integer.valueOf(entityXfRecordProcess.getMealNo());
//            }
//            if (entityXfRecordProcess.getPayState() == null || entityXfRecordProcess.getPayState() == 0 || entityXfRecordProcess.getPayState() == 1) {
//                //判断扣款
//                //计算金额
//                int consMoney = -request.getAmount();
//                entityXfRecordProcess.setConsMoney(Long.valueOf(consMoney));
//                int discount = xfDiscountConfigServcie.selectSiscount(request.getCompanyId(), entityXfAccountInfo.getPId(),
//                        entityXfAccountInfo.getAccTypeId(), request.getConsType(), consTime, intMealNo, request.getAmount(), entityXfRecordProcess);
//                int realMoney = consMoney + discount;
//                //Long chargeBalance=realMoney+entityXfAccountInfo.getAccountRechargeMoney();
//
//                //entiyEntiyXfRecordProcess.setChargeMoney(Long.valueOf(realMoney));
//                //entiyEntiyXfRecordProcess.setSubMoney(0L);
//
//                entityXfRecordProcess.setConsType(request.getConsType());
//                boolean voucher = true;
//
//                //5A、如果设备餐段参数中消费类型、餐段匹配的消费券方式为1-记次模式：
//                String mealNoEntiy = "0";
//                if (entityXfRecordProcess.getMealNo() != null) {
//                    mealNoEntiy = entityXfRecordProcess.getMealNo();
//                }
//                if (entityXfRecordProcess.getXfDeviceMealConfigList() != null) {
//                    for (EntityXfDeviceMealConfig entityXfDeviceMealConfig : entityXfRecordProcess.getXfDeviceMealConfigList()) {
//                        String mealNo = String.valueOf(entityXfDeviceMealConfig.getMealNo());
//                        if (entityXfRecordProcess.getConsType().compareTo(entityXfDeviceMealConfig.getConsType()) == 0 && mealNoEntiy.equals(mealNo)) {
//                            if (entityXfDeviceMealConfig.getVoucherMode() == 1) {
//                                entityXfRecordProcess.setOpTypeDiff(0L);
//                                voucher = false;
//                            }
//                        }
//                    }
//                }
//                entityXfRecordProcess.setDiscount(Long.valueOf(discount));
//                entityXfRecordProcess.setRealMoney(Long.valueOf(realMoney));
//                entityXfRecordProcess.setPayAmount(Long.valueOf(Math.abs(realMoney)));
//                if (voucher) {
//                    //查询扣款顺序
//                    EntityConsTypeConfig entityConsTypeConfig = consTypeConfigService.selectEntityConsTypeConfig(request.getCompanyId(), request.getConsType());
//
//                    //0-不允许代扣，1代扣优先，2最后代扣
//                    int withholdSerial = 0;
//                    //字符串：空表示不允许使用虚拟账户扣款,扣款顺序（1现金钱包、2补贴钱包）
//                    String walletSerial = "21";
//                    if (entityConsTypeConfig != null) {
//                        if (entityConsTypeConfig.getWithholdSerial() != null) {
//                            withholdSerial = entityConsTypeConfig.getWithholdSerial();
//                        }
//                        if (entityConsTypeConfig.getWalletSerial() != null) {
//                            walletSerial = entityConsTypeConfig.getWalletSerial();
//                        }
//                    }
//
//
//                    if (walletSerial.equals("")) {
//                        entityXfRecordProcess.setSubBalance(entityXfAccountInfo.getAccountSubsidyMoney());
//                        entityXfRecordProcess.setChargeBalance(entityXfAccountInfo.getAccountRechargeMoney());
//                        entityXfRecordProcess.setChargeMoney(0L);
//                        entityXfRecordProcess.setSubMoney(0L);
//                    } else if (walletSerial.equals("1")) {
//                        //现金钱包
//                        Long chargeBalance = entityXfRecordProcess.getRealMoney() + entityXfAccountInfo.getAccountRechargeMoney();
//
//                        entityXfRecordProcess.setSubBalance(entityXfAccountInfo.getAccountSubsidyMoney());
//                        entityXfRecordProcess.setChargeBalance(chargeBalance);
//                        entityXfRecordProcess.setChargeMoney(entityXfRecordProcess.getRealMoney());
//                        entityXfRecordProcess.setSubMoney(0L);
//                    } else if (walletSerial.equals("2")) {
//                        //补贴钱包
//                        Long subBalance = entityXfRecordProcess.getRealMoney() + entityXfAccountInfo.getAccountSubsidyMoney();
//                        entityXfRecordProcess.setSubBalance(subBalance);
//                        entityXfRecordProcess.setChargeBalance(entityXfAccountInfo.getAccountRechargeMoney());
//                        entityXfRecordProcess.setSubMoney(entityXfRecordProcess.getRealMoney());
//                        entityXfRecordProcess.setChargeMoney(0L);
//                    } else if (walletSerial.equals("21")) {
//                        //先扣补贴钱包，再扣现金钱包
//                        Long subBalance = entityXfRecordProcess.getRealMoney() + entityXfAccountInfo.getAccountSubsidyMoney();
//                        if (subBalance < 0) {
//                            Long chargeBalance = subBalance + entityXfAccountInfo.getAccountRechargeMoney();
//                            entityXfRecordProcess.setSubBalance(0L);
//                            entityXfRecordProcess.setSubMoney(-entityXfAccountInfo.getAccountSubsidyMoney());
//
//                            entityXfRecordProcess.setChargeBalance(chargeBalance);
//                            entityXfRecordProcess.setChargeMoney(subBalance);
//                        } else {
//                            entityXfRecordProcess.setSubBalance(subBalance);
//                            entityXfRecordProcess.setChargeBalance(entityXfAccountInfo.getAccountRechargeMoney());
//                            entityXfRecordProcess.setSubMoney(entityXfRecordProcess.getRealMoney());
//                            entityXfRecordProcess.setChargeMoney(0L);
//                        }
//                    } else {
//                        //先扣现金钱包，再扣补贴钱包
//                        Long chargeBalance = entityXfRecordProcess.getRealMoney() + entityXfAccountInfo.getAccountRechargeMoney();
//                        if (chargeBalance < 0) {
//                            Long subBalance = chargeBalance + entityXfAccountInfo.getAccountSubsidyMoney();
//
//
//                            entityXfRecordProcess.setSubBalance(subBalance);
//                            entityXfRecordProcess.setSubMoney(chargeBalance);
//
//                            entityXfRecordProcess.setChargeBalance(0L);
//                            entityXfRecordProcess.setChargeMoney(-entityXfAccountInfo.getAccountRechargeMoney());
//                        } else {
//                            entityXfRecordProcess.setSubBalance(entityXfAccountInfo.getAccountSubsidyMoney());
//                            entityXfRecordProcess.setChargeBalance(chargeBalance);
//                            entityXfRecordProcess.setChargeMoney(entityXfRecordProcess.getRealMoney());
//                            entityXfRecordProcess.setSubMoney(0L);
//                        }
//                    }
//                } else {
//                    entityXfRecordProcess.setChargeMoney(0L);
//                    entityXfRecordProcess.setSubMoney(0L);
//                    entityXfRecordProcess.setSubBalance(entityXfAccountInfo.getAccountSubsidyMoney());
//                    entityXfRecordProcess.setChargeBalance(entityXfAccountInfo.getAccountRechargeMoney());
//                }
//            } else {
//                int consMoney = -request.getAmount();
//                entityXfRecordProcess.setConsMoney(Long.valueOf(consMoney));
//
//            }
//            //消费状态，1：消费；2：退款；3：点餐；4.取餐；5.订餐；6：退订；10：充值；11：提现；12：补贴；13：清卡；21：销户
//            entityXfRecordProcess.setConsState(1);
//            entityXfRecordProcess.setOrderNo(orderNo);
//            entityXfRecordProcess.setPayTime(new Date());
//
//            //避免空指针
//            if (entityXfRecordProcess.getMealNo() == null) {
//                entityXfRecordProcess.setMealNo("0");
//            }
//
//            try {
//                if (entityXfRecordProcess.getPayState() == null) {
//                    //支付状态；0支付中、1支付成功，2支付失败，3撤单中，4已撤单，5退款中，6已退款，7部分退款成功
//                    entityXfRecordProcess.setPayState(0);
//                }
//                int i = xfRecordProcessService.insertEntityXfRecord(request.getCompanyId(), entityXfRecordProcess);
//                if (i <= 0) {
//                    log.info("请求方式54:【{}】,机器号:【{}】,请求参数:【{}】,返回:【{}】", "支付请求（保存消费记录）", request.getMachNo(), request, ResultUtil.error(ResultEnum.Err_802));
//                    //订单号重复
//                    return ResultUtil.error(ResultEnum.Err_4002);
//                }
//            } catch (Exception e) {
//                Throwable cause = e.getCause();
//                if (cause instanceof java.sql.SQLIntegrityConstraintViolationException) {
//                    //错误信息
//                    String errMsg = ((java.sql.SQLIntegrityConstraintViolationException) cause).getMessage();
//                    //根据约束名称定位是那个字段
//                    if (StringUtils.isNotBlank(errMsg) && errMsg.indexOf("order_no") != -1) {
//                        return ResultUtil.success("订单号重复");
//                    }
//                }
//                StackTraceElement ste = e.getStackTrace()[0];
//                log.info("请求方式55:【{}】,机器号:【{}】,入库新增等待表的数据4:【{}】,异常的返回:【{}】,行号:【{}】", "支付请求（保存消费记录）", request.getMachNo(), entityXfRecordProcess, e, ste.getLineNumber());
//                log.info("请求方式56:【{}】,机器号:【{}】,请求参数:【{}】,返回:【{}】", "支付请求（保存消费记录）", request.getMachNo(), request, ResultUtil.error(ResultEnum.Err_900));
//                //订单号重复
//                return ResultUtil.error(ResultEnum.Err_4003);
//            }
//            //2023年4月26日17:21:30 菜品缓存表
//            try {
//                if (request.getMenuData() != null && request.getMenuData().size() > 0) {
//                    List<EntityXfGoodsListProcess> entityXfGoodsListProcesses = new ArrayList<>();
//                    if (entityXfRecordProcess.getMerchId() == null) entityXfRecordProcess.setMerchId(0l);
//                    if (entityXfRecordProcess.getDeptId() == null) entityXfRecordProcess.setDeptId(0l);
//                    if (entityXfRecordProcess.getPId() == null) entityXfRecordProcess.setPId(0l);
//                    for (MachMealDataVo menuDataVo : request.getMenuData()) {
//                        EntityXfGoodsListProcess entityXfGoodsListProcess = new EntityXfGoodsListProcess();
//                        entityXfGoodsListProcess.setComId(request.getCompanyId());
//                        entityXfGoodsListProcess.setDeviceNo(entityXfRecordProcess.getDeviceNo());
//                        entityXfGoodsListProcess.setPointId(entityXfRecordProcess.getPointId().intValue());
//                        entityXfGoodsListProcess.setMerchId(entityXfRecordProcess.getMerchId().intValue());
//                        entityXfGoodsListProcess.setPId(entityXfRecordProcess.getPId().longValue());
//                        entityXfGoodsListProcess.setDeptId(entityXfRecordProcess.getDeptId().intValue());
//                        entityXfGoodsListProcess.setReceiptId(0);
//                        entityXfGoodsListProcess.setReceiptName("");
//                        entityXfGoodsListProcess.setOrderNo(entityXfRecordProcess.getOrderNo());
//
//                        entityXfGoodsListProcess.setConsTime(DateUtils.strToDate3(menuDataVo.getEtime(), "yyyyMMddHHmmss"));
//                        entityXfGoodsListProcess.setMealDate(DateUtils.strToDate2(request.getConsDate()));
//                        entityXfGoodsListProcess.setMealNo(request.getConsMeal());
//                        entityXfGoodsListProcess.setConsType(request.getConsType());
//                        entityXfGoodsListProcess.setIfRefund(0);
//                        entityXfGoodsListProcess.setDishesId(menuDataVo.getDishesId());
//                        entityXfGoodsListProcess.setDishesName(menuDataVo.getDishesName());
//                        entityXfGoodsListProcess.setPriceMode(11);
//                        entityXfGoodsListProcess.setWeightNumber(menuDataVo.getNum());
//                        entityXfGoodsListProcess.setDishesPrice(menuDataVo.getPrice());
//                        entityXfGoodsListProcess.setMonthValue(entityXfRecordProcess.getMonthValue());
//                        entityXfGoodsListProcess.setCreateTime(new Date());
//
//                        entityXfGoodsListProcesses.add(entityXfGoodsListProcess);
//                    }
//                    xfGoodsListProcessService.addXfGoodsListProcessList(request.getCompanyId(), entityXfGoodsListProcesses);
//                }
//            } catch (Exception e) {
//                StackTraceElement ste = e.getStackTrace()[0];
//                log.info("请求方式57:【{}】,机器号:【{}】,入库菜品缓存表的数据:【{}】,异常的返回:【{}】,行号:【{}】", "支付请求（保存消费记录）", request.getMachNo(), entityXfRecordProcess, e, ste.getLineNumber());
//                log.info("请求方式58:【{}】,机器号:【{}】,请求参数:【{}】,返回:【{}】", "支付请求（保存消费记录）", request.getMachNo(), request, ResultUtil.error(ResultEnum.Err_900));
//            }
//
//            //异常单不需要入成功表和修改金额
//            if (entityXfRecordProcess.getPayState() != null && entityXfRecordProcess.getPayState() != 0) {
//                return ResultUtil.success();
//            }
//            try {
//
//                EntityXfRecordProcess updateXfRecordProcess = new EntityXfRecordProcess();
//                updateXfRecordProcess.setPayState(1);
//                updateXfRecordProcess.setPayTime(new Date());
//                updateXfRecordProcess.setId(entityXfRecordProcess.getId());
//                updateXfRecordProcess.setMonthValue(DateUtils.getStrDate(newDate, "yyyyMM"));
//
//                entityXfRecordProcess.setMonthValue(DateUtils.getStrDate(newDate, "yyyyMM"));
//                entityXfRecordProcess.setPayState(1);
//                entityXfRecordProcess.setPayTime(updateXfRecordProcess.getPayTime());
//                entityXfRecordProcess.setId(null);
//                try {
//                    xfAccountInfoService.updateAccountTransactional(request.getCompanyId(), entityXfAccountInfo.getId(), entityXfRecordProcess, updateXfRecordProcess);
//                } catch (Exception e) {
//                    StackTraceElement ste = e.getStackTrace()[0];
//                    log.info("请求方式59:【{}】,机器号:【{}】,修改金额的事务:【{}】,异常的返回:【{}】,行号:【{}】", "支付请求（保存消费记录）", request.getMachNo(), entityXfRecordProcess, e, ste.getLineNumber());
//                }
//
//                return ResultUtil.success();
//            } catch (Exception e) {
//                StackTraceElement ste = e.getStackTrace()[0];
//                log.info("请求方式60:【{}】,机器号:【{}】,入库新增等待表的数据5:【{}】,异常的返回:【{}】,行号:【{}】", "支付请求（保存消费记录）", request.getMachNo(), entityXfRecordProcess, e, ste.getLineNumber());
//                log.info("请求方式61:【{}】,机器号:【{}】,请求参数:【{}】,返回:【{}】", "支付请求（保存消费记录）", request.getMachNo(), request, ResultUtil.error(ResultEnum.Err_802));
//                //订单号重复
//                return ResultUtil.error(ResultEnum.Err_4002);
//            }
//        } catch (Exception e) {
//            StackTraceElement ste = e.getStackTrace()[0];
//            log.info("请求方式62:【{}】,机器号:【{}】,入库新增等待表的数据6:【{}】,异常的返回:【{}】,行号:【{}】", "支付请求（保存消费记录）", request.getMachNo(), entityXfRecordProcess, e, ste.getLineNumber());
//            try {
//                if (entityXfRecordProcess.getPayState() == null) {
//                    //支付状态；0支付中、1支付成功，2支付失败，3撤单中，4已撤单，5退款中，6已退款，7部分退款成功
//                    entityXfRecordProcess.setPayState(-105);
//                }
//                if (entityXfRecordProcess.getDeviceName() == null) {
//                    entityXfRecordProcess.setDeviceNo(request.getMachNo());
//                }
//                if (entityXfRecordProcess.getConsTime() == null) {
//                    entityXfRecordProcess.setConsTime(DateUtils.getDate(request.getTradeTime(), DateUtils.YYYY_MM_DD_HH_MM_SS));
//                }
//                if (entityXfRecordProcess.getConsMoney() == null) {
//                    entityXfRecordProcess.setConsMoney(Long.valueOf(-request.getAmount()));
//                }
//                if (entityXfRecordProcess.getPId() == null) {
//                    entityXfRecordProcess.setPId(Long.valueOf(request.getUserId()));
//                }
//                if (entityXfRecordProcess.getOpType() == null || entityXfRecordProcess.getOpTypeDiff() == null) {
//                    //1-刷卡，4-刷脸， 3-ocom离线码
//                    if (request.getType() == 1) {
//                        entityXfRecordProcess.setOpType(1l);
//                        entityXfRecordProcess.setOpTypeDiff(100l);
//                    } else if (request.getType() == 4) {
//                        entityXfRecordProcess.setOpType(22l);
//                        entityXfRecordProcess.setOpTypeDiff(100l);
//                    } else if (request.getType() == 3) {
//                        entityXfRecordProcess.setOpType(21l);
//                        entityXfRecordProcess.setOpTypeDiff(100l);
//                    }
//                }
//                int i = xfRecordProcessService.insertEntityXfRecord(request.getCompanyId(), entityXfRecordProcess);
//                if (i <= 0) {
//                    log.info("请求方式63:【{}】,机器号:【{}】,请求参数:【{}】,返回:【{}】", "支付请求（保存消费记录）", request.getMachNo(), request, ResultUtil.error(ResultEnum.Err_802));
//                    //订单号重复
//                    return ResultUtil.error(ResultEnum.Err_4002);
//                }
//                return ResultUtil.success();
//            } catch (Exception ex) {
//                Throwable cause = ex.getCause();
//                if (cause instanceof java.sql.SQLIntegrityConstraintViolationException) {
//                    //错误信息
//                    String errMsg = ((java.sql.SQLIntegrityConstraintViolationException) cause).getMessage();
//                    //根据约束名称定位是那个字段
//                    if (StringUtils.isNotBlank(errMsg) && errMsg.indexOf("order_no") != -1) {
//                        return ResultUtil.success("订单号重复");
//                    }
//                }
//                StackTraceElement ste1 = e.getStackTrace()[0];
//                log.info("请求方式64:【{}】,机器号:【{}】,入库新增等待表的数据7:【{}】,异常的返回:【{}】,行号:【{}】", "支付请求（保存消费记录）", request.getMachNo(), entityXfRecordProcess, ex, ste1.getLineNumber());
//                log.info("请求方式65:【{}】,机器号:【{}】,请求参数:【{}】,返回:【{}】", "支付请求（保存消费记录）", request.getMachNo(), request, ResultUtil.error(ResultEnum.Err_900));
//                //订单号重复
//                return ResultUtil.error(ResultEnum.Err_4003);
//            }
//
//        }
//    }

    //在线卡消费
//    @PostMapping(PayHandleUrl.getPayCard)
//    public Result onlinePayCard(@RequestBody QrCardPayRequest request) {
//        log.info("【强在线1】【{}】【{}】【{}】",request.getMachNo(),request,"灰度2024年1月8日08:44:41");
//        try {
//            //支付宝支付权限判断
//            if (request.getType() == 9 && !request.getFaceToken().startsWith("AAAA")) {
//                return ResultUtil.error(ResultEnum.Err_3085);
//            }
//
//            String tradeNoRedis = "onlinePay:" + request.getCompanyId() + ":" + request.getMachNo() + ":" + request.getTradeNo();
//            if (redisUtil.lock(tradeNoRedis, 60 * 60)) {
//                //判断是什么支付类型
//                //1-刷卡，4-刷脸，5-付款码，7-ocom离线码 8微信人脸
//                EntityXfAccountInfo entityXfAccountInfo = null;
//                EntityPersonnelInfo entityPersonnelInfo = null;
//                EntityXfRecordProcess entityXfRecordProcess = new EntityXfRecordProcess();
//                EntityCardInfo entityCardInfo = null;
//                if (request.getType() == 1) {
//                    //刷卡
//                    entityCardInfo = xfCardInfoService.selectCard(request.getCompanyId(), request.getAuthCode());
//                    if (entityCardInfo == null) {
//                        return ResultUtil.error(ResultEnum.Err_305);
//                    }
//                    if (entityCardInfo.getCardState() != 1) {
//                        return ResultUtil.error(ResultEnum.Err_4021);
//                    }
//                    String strNewDate = DateUtils.getStrDate(new Date(), "yyyy-MM-dd");
//                    String strEndDate = DateUtils.getStrDate(entityCardInfo.getEndDate(), "yyyy-MM-dd");
//                    if (!DateUtils.compare(strNewDate, strEndDate)) {
//                        return ResultUtil.error(ResultEnum.Err_4025);
//                    }
//                    //用账号查询账号表和人员的信息
//                    entityXfAccountInfo = xfAccountInfoService.selectAccount(request.getCompanyId(), entityCardInfo.getAccountNo());
//                    entityPersonnelInfo = personnelInfoService.selectPersonnel(request.getCompanyId(), entityCardInfo.getPId());
//
//                    //操作类型：
//                    //1：刷卡
//                    //2：付款码支付
//                    //3：免密代扣支付
//                    //4：主扫
//                    //6：优惠卷
//                    //9：订餐
//                    //11：现金充值
//                    //12：线上充值
//                    entityXfRecordProcess.setOpType(1l);
//                    entityXfRecordProcess.setAccountNo(entityCardInfo.getAccountNo());
//                } else {
//
//                    if (request.getType() == 8) {
//                        EntityPersonnelInfo entityPersonnelInfo1 = personnelInfoService.getPersonByPhone(request.getCompanyId(), request.getAuthCode());
//                        if (entityPersonnelInfo1 == null) {
//                            return ResultUtil.error(ResultEnum.Err_4017);
//                        }
//                        request.setAuthCode(entityPersonnelInfo1.getPId().toString());
//                        if (request.getFaceToken() == null) {
//                            return ResultUtil.error(ResultEnum.Err_4027);
//                        }
//                    }
//                    Long pId = 0l;
//                    if (request.getType() == 21) {
//                        if (request.getAuthCode().startsWith("CT")) {
//                            AnalyzeBankUsersVo analyzeBankUsersVo = new AnalyzeBankUsersVo();
//                            analyzeBankUsersVo.setCompanyId(request.getCompanyId());
//                            analyzeBankUsersVo.setAuthCode(request.getAuthCode());
//                            pId = payFunService.AnalyzeBankUsers(analyzeBankUsersVo);
//                            if (pId <= 0l) {
//                                return ResultUtil.error(ResultEnum.Err_4017);
//                            }
//                        } else {
//                            pId = Long.valueOf(request.getAuthCode());
//                        }
//                    } else {
//                        pId = Long.valueOf(request.getAuthCode());
//                    }
//                    entityPersonnelInfo = personnelInfoService.selectPersonnel(request.getCompanyId(), pId);
//                    entityXfAccountInfo = xfAccountInfoService.selectAccountPid(request.getCompanyId(), pId);
//                    entityXfRecordProcess.setAccountNo(entityXfAccountInfo.getAccountNo());
//                    if (request.getType() == 4) {
//                        entityXfRecordProcess.setOpType(22l);
//                    } else if (request.getType() == 7) {
//                        entityXfRecordProcess.setOpType(21l);
//                    } else if (request.getType() == 8) {
//                        //8 微信人脸代扣 22人脸
//                        entityXfRecordProcess.setOpType(22l);
//                    }
//                }
//
//                if (entityXfAccountInfo == null) {
//                    return ResultUtil.error(ResultEnum.Err_816);
//                }
//                if (entityXfAccountInfo.getAccountState() != 0) {
//                    return ResultUtil.error(ResultEnum.Err_4022);
//                }
//
//                if (entityPersonnelInfo == null) {
//                    return ResultUtil.error(ResultEnum.Err_4017);
//                }
//                if (entityPersonnelInfo.getStatus() != 0) {
//                    return ResultUtil.error(ResultEnum.Err_4023);
//                }
//
//                entityXfRecordProcess.setComId(request.getCompanyId());
//                entityXfRecordProcess.setDeviceNo(request.getMachNo());
//                entityXfRecordProcess.setCardNo(request.getAuthCode());
//                entityXfRecordProcess.setAccountNo(entityXfAccountInfo.getAccountNo());
//                entityXfRecordProcess.setPId(entityXfAccountInfo.getPId());
//                entityXfRecordProcess.setPCode(entityPersonnelInfo.getPCode());
//                entityXfRecordProcess.setPName(entityPersonnelInfo.getPName());
//                entityXfRecordProcess.setAccTypeId(entityXfAccountInfo.getAccTypeId());
//                Date date = new Date();
//                entityXfRecordProcess.setCreateTime(date);
//                entityXfRecordProcess.setMonthValue(DateUtils.getStrDate(date, "yyyyMM"));
//                //查询收费的和商家信息
//                relatedDevice(entityXfRecordProcess, request.getCompanyId(), request.getMachNo(), date);
//                if (!payHandleFunService.checkCanPay(request.getConsType(),entityXfRecordProcess, entityXfAccountInfo)) {
//                    return ResultUtil.error(ResultEnum.Err_3098);
//                }
//                if (request.getConsState() == 3 || request.getConsState() == 5) {
//                    payHandleFunService.relatedReceiptNo(entityXfRecordProcess);
//                    if (request.getConsState() == 5) {
//                        payHandleFunService.relatedDingCan(entityXfRecordProcess, request.getConsDate(), request.getConsMeal(), request.getConsPoint());
//                    }
//                }
//                //查询个人所在的组织
//                entityXfRecordProcess.setDeptId(entityPersonnelInfo.getDeptId());
//                if (entityPersonnelInfo.getDeptId() == null) {
//                    entityPersonnelInfo.setDeptId(0l);
//                }
//                EntityDeptInfo entityDeptInfo = deptInfoService.selectDeptName(request.getCompanyId(), entityPersonnelInfo.getDeptId());
//                if (entityDeptInfo != null) {
//                    entityXfRecordProcess.setDeptName(entityDeptInfo.getDeptName());
//                }
//
//                entityXfRecordProcess.setMealDate(DateUtils.getDate(DateUtils.getStrDate(date, DateUtils.YYYY_MM_DD), DateUtils.YYYY_MM_DD));
//                //消费状态，1：消费；2：退款；3：点餐；4.取餐；5.订餐；6：退订；10：充值；11：提现；12：补贴；13：清卡；21：销户
//                entityXfRecordProcess.setConsState(request.getConsState());
//                entityXfRecordProcess.setOrderNo(request.getTradeNo());
//                Integer intMealNo = 0;
//                if (entityXfRecordProcess.getMealNo() != null) {
//                    intMealNo = Integer.valueOf(entityXfRecordProcess.getMealNo());
//                }
//
//                //判断扣款
//                int consMoney = -request.getAmount();
//                //计算金额
//                entityXfRecordProcess.setConsMoney(Long.valueOf(consMoney));
//                //计算优惠
//                entityXfRecordProcess.setConsType(request.getConsType());
//                int discount = xfDiscountConfigServcie.selectSiscount(request.getCompanyId(), entityXfAccountInfo.getPId(),
//                        entityXfAccountInfo.getAccTypeId(), request.getConsType(), date, intMealNo, request.getAmount(), entityXfRecordProcess);
//                int realMoney = consMoney + discount;
//                //查询支付限制
//
//                int limit = xfUserparamConfigService.selectLimit(request.getCompanyId(), entityXfAccountInfo.getPId(),
//                        entityXfAccountInfo.getAccTypeId(), request.getConsType(), date, intMealNo, (Math.abs(realMoney)));
//                if (limit != 0) {
//                    if (limit == 1) {
//                        return ResultUtil.error(ResultEnum.Err_4031);
//                    } else if (limit == 2) {
//                        return ResultUtil.error(ResultEnum.Err_4032);
//                    }
//                    if (limit == 3) {
//                        return ResultUtil.error(ResultEnum.Err_4033);
//                    }
//                    if (limit == 4) {
//                        return ResultUtil.error(ResultEnum.Err_4034);
//                    }
//                    if (limit == 5) {
//                        return ResultUtil.error(ResultEnum.Err_4035);
//                    }
//                    if (limit == 6) {
//                        return ResultUtil.error(ResultEnum.Err_4036);
//                    }
//                }
//                //支付状态；0支付中、1支付成功，2支付失败，3撤单中，4已撤单，5退款中，6已退款，7部分退款成功
//                entityXfRecordProcess.setPayState(0);
//                entityXfRecordProcess.setDiscount(Long.valueOf(discount));
//                entityXfRecordProcess.setRealMoney(Long.valueOf(realMoney));
//                entityXfRecordProcess.setPayAmount(Long.valueOf(Math.abs(realMoney)));
//
//                boolean voucher = true;
//
//                //5A、如果设备餐段参数中消费类型、餐段匹配的消费券方式为1-记次模式：
//                if (entityXfRecordProcess.getXfDeviceMealConfigList() != null && entityXfRecordProcess.getMealNo() != null) {
//                    for (EntityXfDeviceMealConfig entityXfDeviceMealConfig : entityXfRecordProcess.getXfDeviceMealConfigList()) {
//                        String mealNo = String.valueOf(entityXfDeviceMealConfig.getMealNo());
//                        if (entityXfRecordProcess.getConsType().compareTo(entityXfDeviceMealConfig.getConsType()) == 0 && entityXfRecordProcess.getMealNo().equals(mealNo)) {
//                            if (entityXfDeviceMealConfig.getVoucherMode() == 1) {
//                                entityXfRecordProcess.setOpTypeDiff(0L);
//                                voucher = false;
//                            }
//                        }
//                    }
//                }
//                int payState = 0;
//                String walletSerial = "21";
//                if (voucher) {
//                    //查询扣款顺序
//                    EntityConsTypeConfig entityConsTypeConfig = consTypeConfigService.selectEntityConsTypeConfig(request.getCompanyId(), request.getConsType());
//
//                    //0-不允许代扣，1代扣优先，2最后代扣
//                    int withholdSerial = 0;
//                    //字符串：空表示不允许使用虚拟账户扣款,扣款顺序（1现金钱包、2补贴钱包）
//                    if (entityConsTypeConfig != null) {
//                        if (entityConsTypeConfig.getWithholdSerial() != null) {
//                            withholdSerial = entityConsTypeConfig.getWithholdSerial();
//                        }
//                        if (entityConsTypeConfig.getWalletSerial() != null) {
//                            walletSerial = entityConsTypeConfig.getWalletSerial();
//                        }
//                    }
//
//
//                    //第三方的支付失败结果
//                    JSONObject jsonObject = new JSONObject();
//                    //0不允许代扣  1代扣优先  2最后代扣
//                    if (entityXfRecordProcess.getRealMoney() == 0) {
//                        payState = virtual(entityXfRecordProcess, request, entityCardInfo, entityXfAccountInfo, walletSerial);
//                    } else if (withholdSerial == 0) {
//                        if (walletSerial.equals("")) {
//                            return ResultUtil.error(ResultEnum.Err_4038);
//                        }
//                        //不允许代扣
//                        payState = virtual(entityXfRecordProcess, request, entityCardInfo, entityXfAccountInfo, walletSerial);
//                    } else {
//                        //字符串：空表示不允许使用虚拟账户扣款
//                        if (walletSerial.equals("")) {
//                            payState = withholding(entityXfRecordProcess, request, entityCardInfo, jsonObject);
//                            if (payState == 2) {
//                                //支付失败
//                                return ResultUtil.info(3030, jsonObject.getString("msg"));
//                            }
//                        } else {
//                            if (withholdSerial == 1) {
//                                //1代扣优先
//                                payState = withholding(entityXfRecordProcess, request, entityCardInfo, jsonObject);
//                                if (payState != 0 && payState != 1 && payState != -11) {
//                                    entityXfRecordProcess.setOpTypeDiff(null);
//                                    payState = virtual(entityXfRecordProcess, request, entityCardInfo, entityXfAccountInfo, walletSerial);
//                                }
//                            } else {
//                                // 2最后代扣
//                                payState = virtual(entityXfRecordProcess, request, entityCardInfo, entityXfAccountInfo, walletSerial);
//                                if (payState != 0 && payState != 1 && payState != -11) {
//                                    payState = withholding(entityXfRecordProcess, request, entityCardInfo, jsonObject);
//                                }
//                                if (payState == 2) {
//                                    //支付失败
//                                    return ResultUtil.info(3030, jsonObject.getString("msg"));
//                                }
//                            }
//                        }
//                    }
//                } else {
//                    payState = virtual(entityXfRecordProcess, request, entityCardInfo, entityXfAccountInfo, walletSerial);
//                }
//
//
//                if (payState == 1) {
//                    //支付成功
//                    Map<String, Object> map = new HashMap<>();
//                    map.put("discount", entityXfRecordProcess.getDiscount());
//                    map.put("payAmount", Math.abs(entityXfRecordProcess.getRealMoney()));
//                    Map<String, Object> mapAccountInf = new HashMap<>();
//                    mapAccountInf.put("name", entityXfRecordProcess.getPName());
//					/*if (entiyEntiyXfRecordProcess.getChargeBalance()!=null && entiyEntiyXfRecordProcess.getSubBalance()!=null){
//						mapAccountInf.put("money", entiyEntiyXfRecordProcess.getChargeBalance()+entiyEntiyXfRecordProcess.getSubBalance());
//					}else {
//						if (entiyEntiyXfRecordProcess.getChargeBalance()!=null){
//							mapAccountInf.put("money", entiyEntiyXfRecordProcess.getChargeBalance());
//						}
//						if (entiyEntiyXfRecordProcess.getSubBalance()!=null){
//							mapAccountInf.put("money", entiyEntiyXfRecordProcess.getSubBalance());
//						}
//					}
//					mapAccountInf.put("allowance",entityXfAccountInfo.getAccountSubsidyMoney());*/
//                    mapAccountInf.put("money", entityXfRecordProcess.getChargeBalance());
//                    mapAccountInf.put("allowance", entityXfRecordProcess.getSubBalance());
//                    if (entityCardInfo != null) {
//                        mapAccountInf.put("expireDate", DateUtils.getStrDate(entityCardInfo.getEndDate(), DateUtils.YYYY_MM_DD_HH_MM_SS));
//                    }
//                    mapAccountInf.put("cardtype", entityXfAccountInfo.getAccTypeId());
//                    map.put("accountInf", mapAccountInf);
//                    map.put("pickupNum", entityXfRecordProcess.getReceiptNo());
//                    map.put("orderTime", DateUtil.getDateTime(entityXfRecordProcess.getPayTime()));
//                    return ResultUtil.success(map);
//                } else if (payState == -1) {
//                    //商户支付渠道未配置"
//                    return ResultUtil.error(ResultEnum.Err_3048);
//                } else if (payState == -2) {
//                    //代扣未签约"
//                    return ResultUtil.error(ResultEnum.Err_3047);
//                } else if (payState == -11) {
//                    //订单号重复
//                    return ResultUtil.error(ResultEnum.Err_802);
//                } else if (payState == -12) {
//                    //余额不足
//                    return ResultUtil.error(ResultEnum.Err_4024);
//                } else {
//                    //支付结果未知
//                    return ResultUtil.error(ResultEnum.Err_3029);
//                }
//            } else {
//                log.info("请求方式66:【{}】,机器号:【{}】,请求参数:【{}】,返回:【{}】", "支付请求（强在线）", request.getMachNo(), request, ResultUtil.error(ResultEnum.Err_802));
//                //订单号重复
//                return ResultUtil.error(ResultEnum.Err_802);
//            }
//        } catch (Exception e) {
//            StackTraceElement ste = e.getStackTrace()[0];
//            log.info("请求方式67:【{}】,机器号:【{}】,请求参数:【{}】,异常2:【{}】,行号:【{}】", "支付请求（强在线）", request.getMachNo(), request, e, ste.getLineNumber());
//            return ResultUtil.error(ResultEnum.Err_3031);
//        }
//    }

    //查询机器和消费时间等参数
    private void relatedDevice(EntityXfRecordProcess entityXfRecordProcess, Long companyId, String machNo, Date date) {
        //查询收费的和商家信息
        //根据machNo(device_no)查找消费点point_id、商户merch_id
        entityXfRecordProcess.setComId(companyId);
        entityXfRecordProcess.setMerchId(0l);
        entityXfRecordProcess.setPointId(0l);
        entityXfRecordProcess.setDeviceNo(machNo);
        Long timeLong = Long.valueOf(4 * 60 * 60);
        //查询redis是否为空，不为空把值存入redis
        String deviceInfoVoRedis = "xf_device_info#comId:" + companyId + "#machNo:" + machNo + "#";
        Object objectDeviceInfo = redisUtil.get(deviceInfoVoRedis);
        DeviceInfoVo deviceInfoVo = null;
        if (objectDeviceInfo == null) {
            deviceInfoVo = deviceInfoService.selectPointId(companyId, machNo);
            if (deviceInfoVo != null) {
                redisUtil.set(deviceInfoVoRedis, deviceInfoVo, timeLong);
            }
        } else {
            deviceInfoVo = JSON.parseObject(JSON.toJSONString(objectDeviceInfo), DeviceInfoVo.class);
        }

        if (deviceInfoVo != null) {
            entityXfRecordProcess.setDeviceName(deviceInfoVo.getDeviceName());
            entityXfRecordProcess.setPointId(deviceInfoVo.getPointId());
            entityXfRecordProcess.setPointName(deviceInfoVo.getPointName());
            entityXfRecordProcess.setMerchId(deviceInfoVo.getMerchId());
            entityXfRecordProcess.setMerchName(deviceInfoVo.getMerchName());
        }

        //判断消费时间段
        entityXfRecordProcess.setConsTime(date);

        if(entityXfRecordProcess.getAccTypeId()==null){
            entityXfRecordProcess.setAccTypeId(0);
        }
        //查询redis是否为空，不为空把值存入redis
        String mealTimeRedis = "xf_meal_time#comId:" + companyId + "#pointId:" + entityXfRecordProcess.getPointId() + "#accTypeId:"+entityXfRecordProcess.getAccTypeId();
        Object objectMealTime = redisUtil.get(mealTimeRedis);
        List<EntityXfMealTime> mealTimeList = null;
        if (objectMealTime == null) {

            mealTimeList = xfMealTimeService.selectTimeList3(companyId, deviceInfoVo.getPointId(),entityXfRecordProcess.getAccTypeId());

            if (mealTimeList != null) {
                redisUtil.set(mealTimeRedis, mealTimeList, timeLong);
            }
        } else {
            mealTimeList = ObjectList.castList(objectMealTime, EntityXfMealTime.class);
        }

        if (mealTimeList != null) {
            for (EntityXfMealTime entityXfMealTime : mealTimeList) {
                if (DateUtils.isInTimeFor2(date, entityXfMealTime.getBeginTime(), entityXfMealTime.getEndTime())) {
                    entityXfRecordProcess.setMealNo(entityXfMealTime.getMealNo());
                    break;
                }
            }
        }

        //获取消费种类
        String XfDeviceMealConfigRedis = "xf_device_meal_config#comId:" + companyId + "#machNo:" + machNo + "#";
        Object objectXfDeviceMealConfig = redisUtil.get(XfDeviceMealConfigRedis);
        List<EntityXfDeviceMealConfig> deviceMealConfig = null;
        if (objectXfDeviceMealConfig == null) {
            deviceMealConfig = xfDeviceMealConfigServcie.selectVoucher(companyId, machNo);

            if (mealTimeList != null) {
                redisUtil.set(XfDeviceMealConfigRedis, deviceMealConfig, timeLong);
            }
        } else {
            deviceMealConfig = ObjectList.castList(objectXfDeviceMealConfig, EntityXfDeviceMealConfig.class);
        }
        if (deviceMealConfig != null) {
            entityXfRecordProcess.setXfDeviceMealConfigList(deviceMealConfig);
        }
    }

    //查询通道配置
    private EntiyXfMerchPayInfo configure(EntityXfRecordProcess entityXfRecordProcess) {
        EntiyXfMerchPayInfo entiyXfMerchPayInfo = null;
        String xfMerchPayRedis = "xf_merch_pay_info#comId:" + entityXfRecordProcess.getComId() + "#merchId:" + entityXfRecordProcess.getMerchId() + "#";
        Object object = redisUtil.get(xfMerchPayRedis);
        if (entityXfRecordProcess.getOrderNo().startsWith("ZS")) {
            entiyXfMerchPayInfo = xfMerchPayInfoService.selectConfigure(entityXfRecordProcess.getComId(), 0L);
            return entiyXfMerchPayInfo;
        }
        if (object == null) {
            if (entityXfRecordProcess.getPointId() == null || entityXfRecordProcess.getPointId() == 0 || entityXfRecordProcess.getMerchId() == null) {
                entiyXfMerchPayInfo = xfMerchPayInfoService.selectConfigure(entityXfRecordProcess.getComId(), 0L);
            } else {
//                if (entityXfRecordProcess.getComId() == 74l) {
//                    entiyXfMerchPayInfo = getUsefuleMerchPayInfo(entityXfRecordProcess.getComId(), entityXfRecordProcess.getMerchId(), null);
//                } else {
                    //a)pMerID:=merchID，查找商户pMerID有没有支付通道，如果没有找上级商户，直至顶级（pMerID ==0）。
                    entiyXfMerchPayInfo = xfMerchPayInfoService.selectConfigure(entityXfRecordProcess.getComId(), entityXfRecordProcess.getMerchId());
                    if (entiyXfMerchPayInfo == null) {
                        int parentMerchId = Math.toIntExact(entityXfRecordProcess.getMerchId());
                        for (int i = 0; i < 100; i++) {
                            EntityXfMerchantInfo entityXfMerchantInfo = xfMerchantInfoService.selectParentMerchId(entityXfRecordProcess.getComId(), parentMerchId);
                            if (entityXfMerchantInfo != null && entityXfMerchantInfo.getParentMerchId() != null) {
                                parentMerchId = entityXfMerchantInfo.getParentMerchId();
                                entiyXfMerchPayInfo = xfMerchPayInfoService.selectConfigure(entityXfRecordProcess.getComId(), Long.valueOf(parentMerchId));
                                if (entiyXfMerchPayInfo != null) {
                                    break;
                                }
                            }
                            //父级商户id为0不用循环下去了
                            if (parentMerchId == 0) {
                                break;
                            }
                        }
                    }
//                }
            }
//            log.info("查找商户支付信息 - 【{}】 【{}】", entityXfRecordProcess, entiyXfMerchPayInfo);
            Long timeLong = Long.valueOf(4 * 60 * 60);
            redisUtil.set(xfMerchPayRedis, entiyXfMerchPayInfo, timeLong);
        } else {
            entiyXfMerchPayInfo = JSON.parseObject(JSON.toJSONString(object), EntiyXfMerchPayInfo.class);
//            log.info("redis  解析 Json  - 【{}】 【{}】", object, entiyXfMerchPayInfo);
        }
        return entiyXfMerchPayInfo;
    }


    //虚拟账号
    @Deprecated
    private int virtual(EntityXfRecordProcess entityXfRecordProcess, QrCardPayRequest request, EntityCardInfo entityCardInfo,
                        EntityXfAccountInfo entityXfAccountInfo, String walletSerial) {
        entityXfRecordProcess.setPayTime(new Date());
        entityXfRecordProcess.setOrderNo(request.getTradeNo());

        //0、如果扣费通道opTypeDiff等于0，或者实际消费金额realAmount等于0：
        if (entityXfRecordProcess.getOpTypeDiff() == null && entityXfRecordProcess.getRealMoney() != 0) {
            //工本费
            Long gbf = 0L;
            try {
                gbf = xfAccountTypeService.selectGBF(entityXfRecordProcess.getComId(), entityXfAccountInfo.getAccTypeId());
            } catch (Exception exception) {
                StackTraceElement ste = exception.getStackTrace()[0];
                log.info("查找工本费异常 【{}】【{}】", ste.getLineNumber(), exception);
            }

            if (walletSerial.equals("")) {
                entityXfRecordProcess.setSubBalance(entityXfAccountInfo.getAccountSubsidyMoney());
                entityXfRecordProcess.setChargeBalance(entityXfAccountInfo.getAccountRechargeMoney());
                entityXfRecordProcess.setChargeMoney(0L);
                entityXfRecordProcess.setSubMoney(0L);
            } else if (walletSerial.equals("1")) {
                //现金钱包
                Long chargeBalance = entityXfRecordProcess.getRealMoney() + entityXfAccountInfo.getAccountRechargeMoney();
                if (chargeBalance.compareTo(gbf) < 0) {
                    return -12;
                }
                entityXfRecordProcess.setSubBalance(entityXfAccountInfo.getAccountSubsidyMoney());
                entityXfRecordProcess.setChargeBalance(chargeBalance);
                entityXfRecordProcess.setChargeMoney(entityXfRecordProcess.getRealMoney());
                entityXfRecordProcess.setSubMoney(0L);
            } else if (walletSerial.equals("2")) {
                //补贴钱包
                Long subBalance = entityXfRecordProcess.getRealMoney() + entityXfAccountInfo.getAccountSubsidyMoney();
                if (subBalance < 0) {
                    return -12;
                }
                entityXfRecordProcess.setSubBalance(subBalance);
                entityXfRecordProcess.setChargeBalance(entityXfAccountInfo.getAccountRechargeMoney());
                entityXfRecordProcess.setSubMoney(entityXfRecordProcess.getRealMoney());
                entityXfRecordProcess.setChargeMoney(0L);
            } else if (walletSerial.equals("21")) {
                //先扣补贴钱包，再扣现金钱包
                Long subBalance = entityXfRecordProcess.getRealMoney() + entityXfAccountInfo.getAccountSubsidyMoney();
                if (subBalance < 0) {
                    Long chargeBalance = subBalance + entityXfAccountInfo.getAccountRechargeMoney();
                    if (chargeBalance.compareTo(gbf) < 0) {
                        return -12;
                    }

                    entityXfRecordProcess.setSubBalance(0L);
                    entityXfRecordProcess.setSubMoney(-entityXfAccountInfo.getAccountSubsidyMoney());

                    entityXfRecordProcess.setChargeBalance(chargeBalance);
                    entityXfRecordProcess.setChargeMoney(subBalance);
                } else {
                    entityXfRecordProcess.setSubBalance(subBalance);
                    entityXfRecordProcess.setChargeBalance(entityXfAccountInfo.getAccountRechargeMoney());
                    entityXfRecordProcess.setSubMoney(entityXfRecordProcess.getRealMoney());
                    entityXfRecordProcess.setChargeMoney(0L);
                }
            } else {
                //先扣现金钱包，再扣补贴钱包
                Long chargeBalance = entityXfRecordProcess.getRealMoney() + entityXfAccountInfo.getAccountRechargeMoney() - gbf;
                if (chargeBalance < 0) {
                    Long subBalance = chargeBalance + entityXfAccountInfo.getAccountSubsidyMoney();

                    if (subBalance < 0) {
                        return -12;
                    }

                    entityXfRecordProcess.setSubBalance(subBalance);
                    entityXfRecordProcess.setSubMoney(chargeBalance);

                    entityXfRecordProcess.setChargeBalance(gbf);
                    entityXfRecordProcess.setChargeMoney(-entityXfAccountInfo.getAccountRechargeMoney() + gbf);
                } else {
                    entityXfRecordProcess.setSubBalance(entityXfAccountInfo.getAccountSubsidyMoney());
                    entityXfRecordProcess.setChargeBalance(chargeBalance + gbf);
                    entityXfRecordProcess.setChargeMoney(entityXfRecordProcess.getRealMoney());
                    entityXfRecordProcess.setSubMoney(0L);
                }
            }
        } else {
            entityXfRecordProcess.setChargeMoney(0L);
            entityXfRecordProcess.setSubMoney(0L);
            entityXfRecordProcess.setSubBalance(entityXfAccountInfo.getAccountSubsidyMoney());
            entityXfRecordProcess.setChargeBalance(entityXfAccountInfo.getAccountRechargeMoney());
        }

        //100:虚拟账号
        if (entityXfRecordProcess.getOpTypeDiff() == null) {
            entityXfRecordProcess.setOpTypeDiff(100l);
        }
        if (request.getType() == 1) {
            entityXfRecordProcess.setOpType(1l);
        }
        if (request.getType() == 9) {
            entityXfRecordProcess.setOpType(22l);
        }
        try {
            int i = xfRecordProcessService.insertEntityXfRecord(request.getCompanyId(), entityXfRecordProcess);
            if (i <= 0) {
                log.info("请求方式68:【{}】,机器号:【{}】,请求参数:【{}】,返回:【{}】", "支付请求（强在线）", request.getMachNo(), request, ResultUtil.error(ResultEnum.Err_802));
                //订单号重复
                return -11;
            }
        } catch (Exception e) {
            StackTraceElement ste = e.getStackTrace()[0];
            log.info("请求方式69:【{}】,机器号:【{}】,入库新增等待表的数据8:【{}】,异常的返回:【{}】,行号:【{}】", "支付请求（强在线）", request.getMachNo(), entityXfRecordProcess, e, ste.getLineNumber());
            log.info("请求方式70:【{}】,机器号:【{}】,请求参数:【{}】,返回:【{}】", "支付请求（强在线）", request.getMachNo(), request, ResultUtil.error(ResultEnum.Err_802));
            //订单号重复
            return -11;
        }
        try {
            if (request.getConsState() == 3 || request.getConsState() == 5) {
                xfGoodsListProcessService.saveXfGoodsList(request.getCompanyId(), entityXfRecordProcess, request.getMealData());
            }
        } catch (Exception e) {
            StackTraceElement ste = e.getStackTrace()[0];
            log.info("请求方式71:【{}】,机器号:【{}】,虚拟钱包-入库新增菜品缓存表数据的数据:【{}】,异常的返回:【{}】,行号:【{}】", "支付请求（强在线）", request.getMachNo(), entityXfRecordProcess, e, ste.getLineNumber());
        }
        if (entityCardInfo != null) {
            //修改卡流水
            xfCardInfoService.upateCardMoneyA(request.getCompanyId(), entityCardInfo);
        }
        try {

            EntityXfRecordProcess updateXfRecordProcess = new EntityXfRecordProcess();
            updateXfRecordProcess.setPayState(1);
            updateXfRecordProcess.setPayTime(new Date());
            updateXfRecordProcess.setId(entityXfRecordProcess.getId());

            entityXfRecordProcess.setPayState(1);
            entityXfRecordProcess.setPayTime(updateXfRecordProcess.getPayTime());
            entityXfRecordProcess.setId(null);
//			try {
            xfAccountInfoService.updateAccountTransactional(request.getCompanyId(), entityXfAccountInfo.getId(), entityXfRecordProcess, updateXfRecordProcess);
//			}catch (Exception e){
//				StackTraceElement ste =e.getStackTrace()[0];
//				log.info("请求方式:【{}】,机器号:【{}】,修改金额的事务:【{}】,异常的返回:【{}】,行号:【{}】","支付请求（保存消费记录）",request.getMachNo(), entiyEntiyXfRecordProcess,e,ste.getLineNumber());
//			}
            return 1;
        } catch (Exception e) {
            StackTraceElement ste = e.getStackTrace()[0];
            log.info("请求方式72:【{}】,机器号:【{}】,入库新增等待表的数据9:【{}】,异常的返回:【{}】,行号:【{}】", "支付请求（强在线）", request.getMachNo(), entityXfRecordProcess, e, ste.getLineNumber());
            log.info("请求方式73:【{}】,机器号:【{}】,请求参数:【{}】,返回:【{}】", "支付请求（强在线）", request.getMachNo(), request, ResultUtil.error(ResultEnum.Err_802));
            //订单号重复
            return -11;
        }
    }

    //代扣
    //支付状态，0：支付中；1：支付成功；2支付失败；-1：没有代扣通道；-2：未签约；-11：重复订单,-12商户支付渠道未配置,-13
//    @Deprecated
//    private int withholding(EntityXfRecordProcess entityXfRecordProcess, QrCardPayRequest request,
//                            EntityCardInfo entityCardInfo, JSONObject jsonObject) {
//        entityXfRecordProcess.setOrderNo("DK" + entityXfRecordProcess.getOrderNo());
//        boolean withholdSubmerch = false;
//        int parentMerchId = Math.toIntExact(entityXfRecordProcess.getMerchId());
//        //状态流程
//        List<EntityXfChannelInfo> xfChannelInfoList = null;
//        //判断收费点为空和为0是按单位查询
//        if (entityXfRecordProcess.getPointId() == null || entityXfRecordProcess.getPointId() == 0 || entityXfRecordProcess.getMerchId() == null
//                || entityXfRecordProcess.getMerchId() == 0l
//        ) {
//            xfChannelInfoList = xfChannelInfoService.selectPayWay(entityXfRecordProcess.getComId(), 0L);
//        } else {
////            if (entityXfRecordProcess.getComId() == 74l) {
////                Long parentMerchIdLong = getUsefulMerchId(entityXfRecordProcess.getComId(), entityXfRecordProcess.getMerchId());
////                parentMerchId = parentMerchIdLong.intValue();
////                withholdSubmerch = true;
////                xfChannelInfoList = xfChannelInfoService.selectPayWay(entityXfRecordProcess.getComId(), parentMerchIdLong);
////            } else {
//                //a)pMerID:=merchID，查找商户pMerID有没有支付通道，如果没有找上级商户，直至顶级（pMerID ==0）。
//                xfChannelInfoList = xfChannelInfoService.selectPayWay(entityXfRecordProcess.getComId(), entityXfRecordProcess.getMerchId());
//                log.info("查签约号-当前商户 【{}】【{}】", entityXfRecordProcess.getMerchId(), xfChannelInfoList);
//
//                //当前商户信息 判断是否需要上级商户
//                EntityXfMerchantInfo currentXfMerchantInfo = xfMerchantInfoService.selectParentMerchId(entityXfRecordProcess.getComId(), parentMerchId);
//                withholdSubmerch = currentXfMerchantInfo.getWithholdSubmerch();
//
//                if (xfChannelInfoList == null || xfChannelInfoList.size() <= 0 ||
//                        //或者要用商户服务商数据
//                        (currentXfMerchantInfo != null && currentXfMerchantInfo.getWithholdSubmerch() == true)
//                ) {
//                    parentMerchId = currentXfMerchantInfo.getParentMerchId();
//                    for (int i = 0; i < 10; i++) {
//                        EntityXfMerchantInfo entityXfMerchantInfo = xfMerchantInfoService.selectParentMerchId(entityXfRecordProcess.getComId(), parentMerchId);
//                        log.info("查签约号-上级商户 【{}】【{}】", parentMerchId, entityXfMerchantInfo);
//                        //当前商户id判断
//                        if (entityXfMerchantInfo != null && entityXfMerchantInfo.getParentMerchId() != null) {
//                            if (entityXfMerchantInfo.getWithholdSubmerch()) {
//                                parentMerchId = entityXfMerchantInfo.getParentMerchId();
//                                if (parentMerchId == 0) {
//                                    break;
//                                }
//                                continue;
//                            }
//                            xfChannelInfoList = xfChannelInfoService.selectPayWay(entityXfRecordProcess.getComId(), Integer.valueOf(parentMerchId).longValue());
//                            if (xfChannelInfoList != null && xfChannelInfoList.size() > 0) {
//                                break;
//                            } else {
//                                parentMerchId = entityXfMerchantInfo.getParentMerchId();
//                            }
//                        }
//                        //父级商户id为0不用循环下去了
//                        if (parentMerchId == 0) {
//                            break;
//                        }
//                    }
//                }
////            }
//        }
//
//        if (xfChannelInfoList == null || xfChannelInfoList.size() <= 0) {
//            return -1;
//        }
//
//
//        EntityXfSignNo xfSignNo = null;
//        EntityXfSignNo entityXfSignNo = null;
//
//        if (request.getType() == 9) {
//
//            entityXfSignNo = new EntityXfSignNo();
//            entityXfSignNo.setSignNo("");
//            entityXfSignNo.setPayWay(28);
//            xfSignNo = new EntityXfSignNo();
//            xfSignNo.setPayWay(28);
//            entityXfRecordProcess.setOpTypeDiff(308L);
//            entityXfRecordProcess.setOpType(22L);
//        } else {
//            //如果holdwith_submerch==1，则pMerID:= parent_merch_id
//            if (withholdSubmerch) {
//                entityXfSignNo = xfSignNoService.selectSignNo(entityXfRecordProcess.getComId(), Long.valueOf(parentMerchId), entityXfRecordProcess.getPId());
//            } else {
//                entityXfSignNo = xfSignNoService.selectSignNo(entityXfRecordProcess.getComId(), entityXfRecordProcess.getMerchId(), entityXfRecordProcess.getPId());
//            }
//            log.info("查签约号-返回 【{}】【{}】", withholdSubmerch, entityXfSignNo);
//
//            //查询代扣的签约号
//
//            if (entityXfSignNo == null) {
//                //代扣未签约"
//                return -2;
//            }
//
//            //获取所签约的渠道
//            xfSignNo = null;
//
//            for (EntityXfChannelInfo entityXfChannelInfo : xfChannelInfoList) {
//                if (entityXfChannelInfo.getPayWay().compareTo(entityXfSignNo.getPayWay()) == 0) {
//                    xfSignNo = entityXfSignNo;
//                }
//            }
//
//            log.info("查签约号-代扣签约 【{}】【{}】", xfSignNo, xfChannelInfoList);
//
//
//            if (xfSignNo == null) {
//                return -2;
//            }
//
//            //306:建行数字货币代扣,307工行代扣 301 微信代扣
//            if (xfSignNo.getPayWay() != null) {
//                if (xfSignNo.getPayWay() == 7) {
//                    entityXfRecordProcess.setOpTypeDiff(306L);
//                } else if (xfSignNo.getPayWay() == 3) {
//                    entityXfRecordProcess.setOpTypeDiff(307L);
//                } else if (xfSignNo.getPayWay() == 16) {
//                    entityXfRecordProcess.setOpTypeDiff(301L);
//                } else if (xfSignNo.getPayWay() == 28) {
//                    entityXfRecordProcess.setOpTypeDiff(308L);
//                } else if (xfSignNo.getPayWay() == 32) {
//                    try {
//                        return payFunService.CCBWithhold(entityXfRecordProcess, request,
//                                entityCardInfo, jsonObject, xfSignNo);
//                    } catch (Exception exception) {
//                        log.info("【建行生活】【代扣】【异常】参数【{}】缓存数据【{}】异常【{}】", request, entityXfRecordProcess, exception);
//                        return 0;
//                    }
//                }
//                entityXfRecordProcess.setPayWay(xfSignNo.getPayWay());
//            }
//
//        }
//
//        try {
//            int i = xfRecordProcessService.insertEntityXfRecord(request.getCompanyId(), entityXfRecordProcess);
//            if (i <= 0) {
//                log.info("请求方式74:【{}】,机器号:【{}】,请求参数:【{}】,返回:【{}】", "支付请求（强在线,代扣）", request.getMachNo(), request, ResultUtil.error(ResultEnum.Err_802));
//                //订单号重复
//                return -11;
//            }
//        } catch (Exception e) {
//            StackTraceElement ste = e.getStackTrace()[0];
//            log.info("请求方式75:【{}】,机器号:【{}】,入库新增等待表的数据10:【{}】,异常的返回:【{}】,行号:【{}】", "支付请求（强在线,代扣）", request.getMachNo(), entityXfRecordProcess, e, ste.getLineNumber());
//            log.info("请求方式76:【{}】,机器号:【{}】,请求参数:【{}】,返回:【{}】", "支付请求（强在线,代扣）", request.getMachNo(), request, ResultUtil.error(ResultEnum.Err_802));
//            //订单号重复
//            return -11;
//        }
//        try {
//            if (request.getConsState() == 3 || request.getConsState() == 5) {
//                xfGoodsListProcessService.saveXfGoodsList(request.getCompanyId(), entityXfRecordProcess, request.getMealData());
//            }
//        } catch (Exception e) {
//            StackTraceElement ste = e.getStackTrace()[0];
//            log.info("请求方式77:【{}】,机器号:【{}】,代扣-入库新增菜品缓存表数据的数据:【{}】,异常的返回:【{}】,行号:【{}】", "支付请求（强在线）", request.getMachNo(), entityXfRecordProcess, e, ste.getLineNumber());
//        }
//        if (entityCardInfo != null) {
//            //修改卡流水和消费金额
//            xfCardInfoService.upateCardMoneyA(request.getCompanyId(), entityCardInfo);
//        }
//        try {
//            //查询配置信息
//            EntiyXfMerchPayInfo entiyXfMerchPayInfo = configure(entityXfRecordProcess);
//            if (entiyXfMerchPayInfo == null) {
//                //商户支付渠道未配置"
//                return -1;
//            }
//
//            //代扣
//            SignNoHandle signNoHandle = new SignNoHandle();
//            String signNo = signNoHandle.decrypt(entityXfSignNo.getSignNo(), entityXfRecordProcess.getComId());
//            Map<String, Object> retMap = new HashMap<>();
//            retMap.put("company_id", entiyXfMerchPayInfo.getCompanyId());
//            retMap.put("user_name", entiyXfMerchPayInfo.getUserName());
//            retMap.put("password", entiyXfMerchPayInfo.getPassword());
//            retMap.put("pos_no", entityXfRecordProcess.getDeviceNo());
//            retMap.put("fee_type", "CNY");
//            retMap.put("subject", "代扣支付:" + entityXfRecordProcess.getDeviceNo());
//            retMap.put("out_trade_no", entityXfRecordProcess.getOrderNo());
//            retMap.put("contract_id", signNo);
//            retMap.put("total_amount", String.valueOf(Math.abs(entityXfRecordProcess.getRealMoney())));
//            retMap.put("devsnip", "10.68.132.244");
//            retMap.put("body", "代扣支付");
//            retMap.put("pay_channel", String.valueOf(xfSignNo.getPayWay()));
//            retMap.put("tradeTime", DateUtils.getStrDate(entityXfRecordProcess.getConsTime(), "yyyy-MM-dd HH:mm:ss"));
//            retMap.put("user_id", String.valueOf(entityXfRecordProcess.getPId()));
//            retMap.put("lineSymbol", "0");
//            if (xfSignNo.getPayWay() == 16 || xfSignNo.getPayWay() == 28) {
//                retMap.put("user_id", request.getFaceToken());
//            }
//            if (xfSignNo.getPayWay() == 28) {
//                retMap.put("pay_channel", "28");
//                retMap.put("contract_id", request.getUId());
//                retMap.put("aliSignInfo", request.getIotSignInfo());
//                retMap.put("lineSymbol", 1);
//            }
//            //向统一支付平台发起支付
//            String json = HttpUtils.postJson(payUrl + "/withholding/pay.do", retMap);
//            JSONObject results = JSON.parseObject(json);
//            EntityXfRecordProcess updateXfRecordProcess = new EntityXfRecordProcess();
//            updateXfRecordProcess.setId(entityXfRecordProcess.getId());
//            updateXfRecordProcess.setPayChannelNo(entiyXfMerchPayInfo.getCompanyId());
//            updateXfRecordProcess.setComId(entityXfRecordProcess.getComId());
//            if (results.getInteger("code") == 200) {
//                //支付成功，修改等待表的状态和把数据入成功表
//                Map<String, String> dataMap = (Map<String, String>) JSON.parse(results.getString("data"));
//                updateXfRecordProcess.setChannelOrderNo(dataMap.get("trade_no"));
//                updateXfRecordProcess.setPayTime(DateUtil.getDate(dataMap.get("time_end"), "yyyyMMddHHmmss"));
//                updateXfRecordProcess.setPayState(1);
//                updateXfRecordProcess.setPayWay(PayWar.getPayWar(dataMap.get("trade_type")));
//                if (!CommonUtil.isNull(dataMap.get("body"))) {
//                    if (dataMap.get("body").startsWith("dianzi")) {
//                        updateXfRecordProcess.setReserved3("支付宝垫资");
//                    }
//                }
//                try {
//                    int i = xfRecordProcessService.updateEntityXfRecord(updateXfRecordProcess.getComId(), updateXfRecordProcess);
//                    if (i <= 0) {
//                        log.info("请求方式78:【{}】,机器号:【{}】,入库修改的数据:【{}】,返回:【{}】", "支付请求（强在线）", entityXfRecordProcess.getDeviceNo(), updateXfRecordProcess, "等待表修改入库失败");
//                        log.info("请求方式79:【{}】,机器号:【{}】,统一支付平台的请求参数:【{}】,统一支付平台的返回:【{}】", "支付请求（强在线）", entityXfRecordProcess.getDeviceNo(), retMap, json);
//
//                    }
//                } catch (Exception e) {
//                    StackTraceElement ste = e.getStackTrace()[0];
//                    log.info("请求方式80:【{}】,机器号:【{}】,入库修改的数据:【{}】,异常的返回:【{}】,行号:【{}】", "支付请求（强在线）", entityXfRecordProcess.getDeviceNo(), updateXfRecordProcess, e, ste.getLineNumber());
//                    log.info("请求方式81:【{}】,机器号:【{}】,统一支付平台的请求参数:【{}】,统一支付平台的返回:【{}】", "支付请求（强在线）", entityXfRecordProcess.getDeviceNo(), retMap, json);
//                }
//
//                entityXfRecordProcess.setPayTime(updateXfRecordProcess.getPayTime());
//                entityXfRecordProcess.setId(null);
//                entityXfRecordProcess.setChannelOrderNo(dataMap.get("trade_no"));
//                entityXfRecordProcess.setPayWay(PayWar.getPayWar(dataMap.get("trade_type")));
//                entityXfRecordProcess.setPayState(1);
//                entityXfRecordProcess.setPayTime(updateXfRecordProcess.getPayTime());
//                entityXfRecordProcess.setPayChannelNo(updateXfRecordProcess.getPayChannelNo());
//                EntityXfRecord entityXfRecord = JSONObject.parseObject(JSON.toJSONString(entityXfRecordProcess), EntityXfRecord.class);
//                Result result = xfRecordFeign.sveXfRecord(entityXfRecord);
//                if (result.getCode() != 200) {
//                    log.info("请求方式82:【{}】,机器号:【{}】,入库成功的数据:【{}】,返回:【{}】", "支付请求（强在线）", entityXfRecordProcess.getDeviceNo(), updateXfRecordProcess, "添加入库失败");
//                    log.info("请求方式83:【{}】,机器号:【{}】,请求参数:【{}】,请求入xfrecode的表数据的返回的参数:【{}】", "支付请求（强在线）", entityXfRecordProcess.getDeviceNo(), retMap, result);
//                }
//                try {
//                    if (request.getConsState() == 3 || request.getConsState() == 5) {
//                        xfGoodsListProcessService.saveXfGoodsListRecode(request.getCompanyId(), entityXfRecordProcess.getOrderNo());
//                    }
//                } catch (Exception e) {
//                    StackTraceElement ste = e.getStackTrace()[0];
//                    log.info("请求方式84:【{}】,机器号:【{}】,代扣-入库新增菜品成功表数据的数据:【{}】,异常的返回:【{}】,行号:【{}】", "支付请求（强在线）", request.getMachNo(), entityXfRecordProcess, e, ste.getLineNumber());
//                }
//                return 1;
//            } else if (results.getInteger("code") == 16 || results.getInteger("code") == 19
//                    || results.getInteger("code") == 7 || json.contains("Exception")) {
//                //支付结果未知
//                return 0;
//            } else {
//                updateXfRecordProcess.setPayState(2);
//                try {
//                    int i = xfRecordProcessService.updateEntityXfRecord(entityXfRecordProcess.getComId(), updateXfRecordProcess);
//                    if (i <= 0) {
//                        log.info("请求方式85:【{}】,机器号:【{}】,入库修改的数据:【{}】,返回:【{}】", "支付请求（强在线）", entityXfRecordProcess.getDeviceNo(), updateXfRecordProcess, "等待表修改入库失败");
//                        log.info("请求方式86:【{}】,机器号:【{}】,统一支付平台的请求参数:【{}】,统一支付平台的返回:【{}】", "支付请求（强在线）", entityXfRecordProcess.getDeviceNo(), retMap, json);
//
//                    }
//                } catch (Exception e) {
//                    StackTraceElement ste = e.getStackTrace()[0];
//                    log.info("请求方式87:【{}】,机器号:【{}】,入库修改的数据:【{}】,异常的返回:【{}】,行号:【{}】", "支付请求（强在线）", entityXfRecordProcess.getDeviceNo(), updateXfRecordProcess, e, ste.getLineNumber());
//                    log.info("请求方式88:【{}】,机器号:【{}】,统一支付平台的请求参数:【{}】,统一支付平台的返回:【{}】", "支付请求（强在线）", entityXfRecordProcess.getDeviceNo(), retMap, json);
//                }
//                log.info("请求方式89:【{}】,机器号:【{}】,统一支付平台的请求参数:【{}】,统一支付平台的返回:【{}】", "支付请求（强在线）", entityXfRecordProcess.getDeviceNo(), retMap, json);
//                jsonObject.put("msg", results.get("msg"));
//                return 2;
//            }
//        } catch (Exception e) {
//            StackTraceElement ste = e.getStackTrace()[0];
//            log.info("请求方式90:【{}】,机器号:【{}】,入库新增等待表的数据11:【{}】,异常的返回:【{}】,行号:【{}】", "支付请求（强在线）", request.getMachNo(), entityXfRecordProcess, e, ste.getLineNumber());
//            log.info("请求方式91:【{}】,机器号:【{}】,请求参数:【{}】,返回:【{}】", "支付请求（强在线）", request.getMachNo(), request, ResultUtil.error(ResultEnum.Err_802));
//            //订单号重复
//            return -11;
//        }
//    }

    /**
     * 代扣子商户获取代扣顶级签约号
     *
     * @return 递归商户号
     */
    @Deprecated
    private Long getUsefulMerchId(Long comId, Long merchId) {
        if (merchId == 0 || merchId == null) {
            return 0l;
        }
        EntityXfMerchantInfo entityXfMerchantInfo = xfMerchantInfoService.selectParentMerchId(comId, merchId.intValue());
        if (entityXfMerchantInfo == null) {
            return 0l;
        }
        //如果是代扣 子商户
        if (entityXfMerchantInfo.getWithholdSubmerch()) {
            if (entityXfMerchantInfo.getParentMerchId() == null) {
                return 0l;
            }
            return getUsefulMerchId(comId, entityXfMerchantInfo.getParentMerchId().longValue());
        } else {
            return merchId;
        }
    }

    /**
     * 设备消费记录
     *
     * @param request
     * @return
     */
    @PostMapping(PayHandleUrl.URL_machBillList)
    public Result machBillList(@Valid @RequestBody QrCodeBillListRequest request) {
        try {

            Long  pId =0l;
            if(request.getType()!=0){
                try {
                    //判断是什么支付类型
                    //1-刷卡，4-刷脸，5-付款码，7-ocom离线码 8微信人脸
                    if (request.getType() == 1) {
                        //刷卡
                        EntityCardInfo entityCardInfo = xfCardInfoService.selectCard(request.getCompanyID(), request.getAuthCode());
                        if (entityCardInfo == null) {
                            return ResultUtil.error(ResultEnum.Err_305);
                        }
                        if (entityCardInfo.getCardState() != 1) {
                            return ResultUtil.error(ResultEnum.Err_4021);
                        }
                        String strNewDate = DateUtils.getStrDate(new Date(), "yyyy-MM-dd");
                        String strEndDate = DateUtils.getStrDate(entityCardInfo.getEndDate(), "yyyy-MM-dd");
                        if (!DateUtils.compare(strNewDate, strEndDate)) {
                            return ResultUtil.error(ResultEnum.Err_4025);
                        }
                        //用账号查询账号表和人员的信息
                        pId = entityCardInfo.getPId() ;
                    } else {
                        if (request.getType() == 21) {
                            if (request.getAuthCode().startsWith("CT")) {
                                AnalyzeBankUsersVo analyzeBankUsersVo = new AnalyzeBankUsersVo();
                                analyzeBankUsersVo.setCompanyId(request.getCompanyID());
                                analyzeBankUsersVo.setAuthCode(request.getAuthCode());
                                pId = payFunService.AnalyzeBankUsers(analyzeBankUsersVo);
                                if (pId <= 0l) {
                                    return ResultUtil.error(ResultEnum.Err_4017);
                                }
                            } else {
                                pId = Long.valueOf(request.getAuthCode());
                            }
                        } else {
                            pId = Long.valueOf(request.getAuthCode());
                        }
                    }
                }catch (Exception exception){
                    log.info("机器 【{}】 参数 【{}】 查询人员id异常  【{}】",request.getMachNo(),request,exception);
                    return ResultUtil.error(ResultEnum.Err_4017);
                }
            }

            PageInfo<EntityXfRecordProcess> processPageInfo = xfRecordProcessService.selectPageInfo(request.getCompanyID(), request,pId);
            if (processPageInfo.getList().size() <= 0) {
                return ResultUtil.error(ResultEnum.Err_1001);
            }
            List<Map<String, Object>> mapList = new ArrayList<>();
            for (EntityXfRecordProcess entityXfRecordProcess : processPageInfo.getList()) {
                Map<String, Object> map = new HashMap<>();
                map.put("out_trade_no", entityXfRecordProcess.getOrderNo());
                map.put("total_money", Math.abs(entityXfRecordProcess.getRealMoney()));
                int opTypeDiff = Math.toIntExact(entityXfRecordProcess.getOpTypeDiff());
                int opType = Math.toIntExact(entityXfRecordProcess.getOpType());
                map.put("pay_type", OpTypeEnum.getName(opType) + "(" + OpTypeDiffEnum.getName(opTypeDiff) + ")");
                map.put("time", DateUtils.getStrDate(entityXfRecordProcess.getConsTime(), DateUtils.YYYY_MM_DD_HH_MM_SS));
                map.put("pay_status", entityXfRecordProcess.getIfRefund() <= 0 ? 1 : 2);
                map.put("receipt_no", entityXfRecordProcess.getReceiptNo());
                if (opType == 2) {
                    map.put("tradeType", 2);
                } else {
                    map.put("tradeType", 1);
                }
                map.put("p_name", entityXfRecordProcess.getPName());
                mapList.add(map);
            }
            Map<String, Object> reMap = new HashMap<>();
            reMap.put("orderData_s", mapList);
            reMap.put("total", processPageInfo.getTotal());
            return ResultUtil.success(reMap);
        } catch (Exception e) {
            StackTraceElement ste = e.getStackTrace()[0];
            log.info("请求方式:【{}】,机器号:【{}】,请求参数:【{}】,异常:【{}】,行号:【{}】", "设备消费记录", request.getMachNo(), request, e, ste.getLineNumber());
            return ResultUtil.error(ResultEnum.Err_3031);
        }
    }

    /**
     * 设备消费日报表
     *
     * @param request
     * @return
     */
    @PostMapping(PayHandleUrl.URL_machDailySummary)
    public Result machDailySummary(@Valid @RequestBody QrCodeMachDailySummaryRequest request) {
        try {
            List<EntityXfRecordProcess> processPageInfo = xfRecordProcessService.selectMachDailySummary(request.getCompanyId(), request);
            if (processPageInfo.size() <= 0) {
                return ResultUtil.error(ResultEnum.Err_1001);
            }
            List<Map<String, Object>> mapList = new ArrayList<>();
            EntityCompanyInfo entityCompanyInfo = companyInfoService.GetCompanyInfo(request.getCompanyId());
            if (null != entityCompanyInfo && 1 == entityCompanyInfo.getDailySummary()) {
                processPageInfo = xfRecordProcessService.selectMachDailySummary2(request.getCompanyId(), request);
                Result mealResult = payConfigClientService.GetMealNameInfo(request.getCompanyId());
                Map<String, Object> mealMap = new HashMap<>();

                if (200 == mealResult.getCode() && null != mealResult.getData()) {
                    Map<String, Object> mealResultMap = JSON.parseObject(JSON.toJSONString(mealResult.getData()), Map.class);
                    List<EntityXfMealInfo> entityXfMealInfos = JSON.parseArray(JSON.toJSONString(mealResultMap.get("list")), EntityXfMealInfo.class);
                    mealMap = entityXfMealInfos.stream().collect(Collectors.toMap(e -> e.getMealNo(), e -> e.getMealName(), (e1, e2) -> e1));
                }
                for (EntityXfRecordProcess entityXfRecordProcess : processPageInfo) {
                    Map<String, Object> map = new HashMap<>();
                    map.put("amount", -entityXfRecordProcess.getAmount());
                    map.put("times", entityXfRecordProcess.getTimes());
                    map.put("payMode", mealMap.get(entityXfRecordProcess.getMealNo()));
                    mapList.add(map);
                }
            } else {
                for (EntityXfRecordProcess entityXfRecordProcess : processPageInfo) {
                    Map<String, Object> map = new HashMap<>();
                    map.put("amount", -entityXfRecordProcess.getAmount());
                    map.put("times", entityXfRecordProcess.getTimes());
                    int opTypeDiff = Math.toIntExact(entityXfRecordProcess.getOpTypeDiff());
                    int opType = Math.toIntExact(entityXfRecordProcess.getOpType());
                    map.put("payMode", OpTypeEnum.getName(opType) + "(" + OpTypeDiffEnum.getName(opTypeDiff) + ")");
                    mapList.add(map);
                }
            }

            Map<String, Object> reMap = new HashMap<>();
            reMap.put("payData", mapList);
            return ResultUtil.success(reMap);
        } catch (Exception e) {
            StackTraceElement ste = e.getStackTrace()[0];
            log.info("请求方式92:【{}】,机器号:【{}】,请求参数:【{}】,异常:【{}】,行号:【{}】", "设备消费日报表", request.getMachNo(), request, e, ste.getLineNumber());
            return ResultUtil.error(ResultEnum.Err_3031);
        }
    }

    private EntiyXfMerchPayInfo configureAuthinfo(AuthinfoRequest request) {

        long pointId = 0L;
        long merchId = 0L;
        Long timeLong = Long.valueOf(4 * 60 * 60);
        //查询redis是否为空，不为空把值存入redis
        String deviceInfoVoRedis = "xf_device_info#comId:" + request.getCompanyId() + "#machNo:" + request.getMachNo() + "#";
        Object objectDeviceInfo = redisUtil.get(deviceInfoVoRedis);
        DeviceInfoVo deviceInfoVo = null;
        if (objectDeviceInfo == null) {
            deviceInfoVo = deviceInfoService.selectPointId(request.getCompanyId(), request.getMachNo());
            if (deviceInfoVo != null) {
                redisUtil.set(deviceInfoVoRedis, deviceInfoVo, timeLong);
            }
        } else {
            deviceInfoVo = JSON.parseObject(JSON.toJSONString(objectDeviceInfo), DeviceInfoVo.class);
        }

        if (deviceInfoVo != null) {
            merchId = deviceInfoVo.getMerchId();
            pointId = deviceInfoVo.getPointId();
        }


        EntiyXfMerchPayInfo entiyXfMerchPayInfo = null;
        String xfMerchPayRedis = "xf_merch_pay_info#comId:" + request.getCompanyId() + "#merchId:" + merchId + "#";
        Object object = redisUtil.get(xfMerchPayRedis);
        if (object == null) {
            if (pointId == 0 || merchId == 0) {
                entiyXfMerchPayInfo = xfMerchPayInfoService.selectConfigure(request.getCompanyId(), 0L);
            } else {
//                if (request.getCompanyId() == 74l) {
//                    entiyXfMerchPayInfo = getUsefuleMerchPayInfo(request.getCompanyId(), merchId, null);
//                } else {
                    //a)pMerID:=merchID，查找商户pMerID有没有支付通道，如果没有找上级商户，直至顶级（pMerID ==0）。
                    entiyXfMerchPayInfo = xfMerchPayInfoService.selectConfigure(request.getCompanyId(), merchId);
                    if (entiyXfMerchPayInfo == null) {
                        int parentMerchId = Math.toIntExact(merchId);
                        for (int i = 0; i < 100; i++) {
                            EntityXfMerchantInfo entityXfMerchantInfo = xfMerchantInfoService.selectParentMerchId(request.getCompanyId(), parentMerchId);
                            if (entityXfMerchantInfo != null && entityXfMerchantInfo.getParentMerchId() != null) {
                                parentMerchId = entityXfMerchantInfo.getParentMerchId();
                                entiyXfMerchPayInfo = xfMerchPayInfoService.selectConfigure(request.getCompanyId(), Long.valueOf(parentMerchId));
                                if (entiyXfMerchPayInfo != null) {
                                    break;
                                }
                            }
                            //父级商户id为0不用循环下去了
                            if (parentMerchId == 0) {
                                break;
                            }
                        }
                    }
//                }
            }
            redisUtil.set(xfMerchPayRedis, entiyXfMerchPayInfo, timeLong);
        } else {
            entiyXfMerchPayInfo = JSON.parseObject(JSON.toJSONString(object), EntiyXfMerchPayInfo.class);
//            log.info("redis  解析 Json  - 【{}】 【{}】", object, entiyXfMerchPayInfo);
        }
        return entiyXfMerchPayInfo;
    }

    /**
     * 递归查找可用统一支付编号
     *
     * @param comId    单位
     * @param merchId  商户
     * @param merchIds 传null 已配通道商户
     * @return
     */
    private EntiyXfMerchPayInfo getUsefuleMerchPayInfo(Long comId, Long merchId, List<Integer> merchIds) {
        if (merchId == null || merchId == 0l) {
            EntiyXfMerchPayInfo entiyXfMerchPayInfo = xfMerchPayInfoService.selectConfigure(comId, 0L);
            return entiyXfMerchPayInfo;
        }
        if (merchIds == null || merchIds.size() == 0) {
            List<EntityXfChannelInfo> channelInfoList = xfChannelInfoService.selectPayWay(comId);
            if (channelInfoList == null || channelInfoList.size() == 0) {
                return null;
            }
            merchIds = channelInfoList.stream().map(EntityXfChannelInfo -> EntityXfChannelInfo.getMerchId()).collect(Collectors.toList());
        }
        //未配往上找
        if (!merchIds.contains(merchId.intValue())) {
            EntityXfMerchantInfo entityXfMerchantInfo = xfMerchantInfoService.selectParentMerchId(comId, merchId.intValue());
            if (entityXfMerchantInfo == null) {
                EntiyXfMerchPayInfo entiyXfMerchPayInfo = xfMerchPayInfoService.selectConfigure(comId, 0L);
                return entiyXfMerchPayInfo;
            }
            return getUsefuleMerchPayInfo(comId, entityXfMerchantInfo.getParentMerchId().longValue(), merchIds);
        } else {
            EntiyXfMerchPayInfo entiyXfMerchPayInfo = xfMerchPayInfoService.selectConfigure(comId, merchId);
            return entiyXfMerchPayInfo;
        }
    }

    //获取微信人脸授权信息
    @PostMapping(PayHandleUrl.URL_WX_Authinfo)
    public Result WXAuthinfo(@RequestBody AuthinfoRequest request) {
        try {
            //查询配置信息
            EntiyXfMerchPayInfo entiyXfMerchPayInfo = configureAuthinfo(request);
            if (entiyXfMerchPayInfo == null) {
                //商户支付渠道未配置"
                return ResultUtil.error(ResultEnum.Err_3048);
            }
            Map<String, Object> retMap = new HashMap<>();
            retMap.put("company_id", entiyXfMerchPayInfo.getCompanyId());
            retMap.put("user_name", entiyXfMerchPayInfo.getUserName());
            retMap.put("password", entiyXfMerchPayInfo.getPassword());
            retMap.put("now", System.currentTimeMillis());
            retMap.put("version", "1");
            retMap.put("store_id", "GROUP_DINING");
            retMap.put("store_name", "GROUP_DINING");
            retMap.put("device_id", request.getDeviceId());
            retMap.put("rawdata", request.getRawdata());

            //向统一支付平台发起支付
            String payUrl = companyInfoService.getPayCenterUrl(request.getCompanyId(), entiyXfMerchPayInfo.getCompanyId());
            String json = HttpUtils.postJson(payUrl + "/offlineFacepay/authinfo.do", retMap);
            JSONObject results = JSON.parseObject(json);

            if (results.getInteger("code") == 200) {
                Map<String, String> dataMap = (Map<String, String>) JSON.parse(results.getString("data"));
//				Map<String,Object> map=new HashMap<>();
//				map.put("authinfo",dataMap.get("authinfo"));
//				map.put("authinfo",dataMap.get("authinfo"));
                return ResultUtil.success(dataMap);
            } else {
//                log.info("请求方式93:【{}】,机器号:【{}】,统一支付平台的请求参数:【{}】,统一支付平台的返回:【{}】", "获取微信人脸授权信息", request.getMachNo(), retMap, json);
                return ResultUtil.info(3030, results.getString("msg"));
            }
        } catch (Exception e) {
            StackTraceElement ste = e.getStackTrace()[0];
//            log.info("请求方式94:【{}】,机器号:【{}】,请求参数:【{}】,异常:【{}】,行号:【{}】", "获取微信人脸授权信息", request.getMachNo(), request, e, ste.getLineNumber());
            return ResultUtil.error(ResultEnum.Err_3031);
        }
    }

    //充值请求（onlineDeposit）
    @PostMapping(PayHandleUrl.URL_onlineDeposit)
    public Result onlineDeposit(@RequestBody RechargeCardRequest request) {
        try {
            String tradeNoRedis = "onlineDeposit:" + request.getCompanyId() + ":" + request.getMachNo() + ":" + request.getTradeNo();
            if (redisUtil.lock(tradeNoRedis, 60 * 60)) {
//判断是什么支付类型
                //1-刷卡，4-刷脸，5-付款码，7-ocom离线码
                EntityXfAccountInfo entityXfAccountInfo = null;
                EntityPersonnelInfo entityPersonnelInfo = null;
                EntityXfRecordProcess entityXfRecordProcess = new EntityXfRecordProcess();
                EntityCardInfo entityCardInfo = null;
                if (request.getType() == 1) {
                    //刷卡
                    entityCardInfo = xfCardInfoService.selectCard(request.getCompanyId(), request.getCardNum());
                    if (entityCardInfo == null) {
                        return ResultUtil.error(ResultEnum.Err_305);
                    }
                    if (entityCardInfo.getCardState() != 1) {
                        return ResultUtil.error(ResultEnum.Err_4021);
                    }
                    String strNewDate = DateUtils.getStrDate(new Date(), "yyyy-MM-dd");
                    String strEndDate = DateUtils.getStrDate(entityCardInfo.getEndDate(), "yyyy-MM-dd");
                    if (!DateUtils.compare(strNewDate, strEndDate)) {
                        return ResultUtil.error(ResultEnum.Err_4025);
                    }
                    //用账号查询账号表和人员的信息
                    entityXfAccountInfo = xfAccountInfoService.selectAccount(request.getCompanyId(), entityCardInfo.getAccountNo());
                    entityPersonnelInfo = personnelInfoService.selectPersonnel(request.getCompanyId(), entityCardInfo.getPId());

                    //操作类型：
                    //1：刷卡
                    //2：付款码支付
                    //3：免密代扣支付
                    //4：主扫
                    //6：优惠卷
                    //9：订餐
                    //11：现金充值
                    //12：线上充值
                    entityXfRecordProcess.setOpType(1l);
                    entityXfRecordProcess.setAccountNo(entityCardInfo.getAccountNo());
                } else {

                    Long pId = Long.valueOf(request.getCardNum());
                    entityPersonnelInfo = personnelInfoService.selectPersonnel(request.getCompanyId(), pId);
                    entityXfAccountInfo = xfAccountInfoService.selectAccountPid(request.getCompanyId(), pId);
                    entityXfRecordProcess.setAccountNo(entityXfAccountInfo.getAccountNo());
                    if (request.getType() == 4) {
                        entityXfRecordProcess.setOpType(22l);
                    } else if (request.getType() == 7) {
                        entityXfRecordProcess.setOpType(21l);
                    }
                }

                if (entityXfAccountInfo == null) {
                    return ResultUtil.error(ResultEnum.Err_816);
                }
                if (entityXfAccountInfo.getAccountState() != 0) {
                    return ResultUtil.error(ResultEnum.Err_4022);
                }

                if (entityPersonnelInfo == null) {
                    return ResultUtil.error(ResultEnum.Err_4017);
                }
                if (entityPersonnelInfo.getStatus() != 0) {
                    return ResultUtil.error(ResultEnum.Err_4023);
                }
                entityXfRecordProcess.setOpTypeDiff(1L);
                entityXfRecordProcess.setComId(request.getCompanyId());
                entityXfRecordProcess.setDeviceNo(request.getMachNo());
                entityXfRecordProcess.setCardNo(request.getCardNum());
                entityXfRecordProcess.setAccountNo(entityXfAccountInfo.getAccountNo());
                entityXfRecordProcess.setPId(entityXfAccountInfo.getPId());
                entityXfRecordProcess.setPCode(entityPersonnelInfo.getPCode());
                entityXfRecordProcess.setPName(entityPersonnelInfo.getPName());
                Date date = new Date();
                entityXfRecordProcess.setCreateTime(date);
                entityXfRecordProcess.setMonthValue(DateUtils.getStrDate(date, "yyyyMM"));
                //查询收费的和商家信息
                relatedDevice(entityXfRecordProcess, request.getCompanyId(), request.getMachNo(), date);
                //查询个人所在的组织
                entityXfRecordProcess.setDeptId(entityPersonnelInfo.getDeptId());
                EntityDeptInfo entityDeptInfo = deptInfoService.selectDeptName(request.getCompanyId(), entityPersonnelInfo.getDeptId());
                if (entityDeptInfo != null) {
                    entityXfRecordProcess.setDeptName(entityDeptInfo.getDeptName());
                }

                entityXfRecordProcess.setMealDate(DateUtils.getDate(DateUtils.getStrDate(date, DateUtils.YYYY_MM_DD), DateUtils.YYYY_MM_DD));
                //消费状态，1：消费；2：退款；3：点餐；4.取餐；5.订餐；6：退订；10：充值；11：提现；12：补贴；13：清卡；21：销户
                entityXfRecordProcess.setConsState(10);
                entityXfRecordProcess.setOrderNo(request.getTradeNo());
                entityXfRecordProcess.setConsTime(date);
                //判断扣款
                int consMoney = request.getAmount();
                //计算金额
                entityXfRecordProcess.setConsMoney(Long.valueOf(consMoney));
                //计算优惠
                entityXfRecordProcess.setConsType(request.getConsType());
                int discount = 0;
                int realMoney = consMoney + discount;

                //支付状态；0支付中、1支付成功，2支付失败，3撤单中，4已撤单，5退款中，6已退款，7部分退款成功
                entityXfRecordProcess.setPayState(0);
                entityXfRecordProcess.setDiscount(Long.valueOf(discount));
                entityXfRecordProcess.setRealMoney(Long.valueOf(realMoney));
                entityXfRecordProcess.setPayAmount(Long.valueOf(-realMoney));
                entityXfRecordProcess.setOrderNo("CZ" + request.getTradeNo());

                entityXfRecordProcess.setSubBalance(entityXfAccountInfo.getAccountSubsidyMoney());
                entityXfRecordProcess.setChargeBalance(entityXfAccountInfo.getAccountRechargeMoney() + realMoney);
                entityXfRecordProcess.setChargeMoney(Long.valueOf(realMoney));
                entityXfRecordProcess.setSubMoney(0L);
                try {
                    int i = xfRecordProcessService.insertEntityXfRecord(request.getCompanyId(), entityXfRecordProcess);
                    if (i <= 0) {
                        log.info("请求方式95:【{}】,机器号:【{}】,请求参数:【{}】,返回:【{}】", "充值请求", request.getMachNo(), request, ResultUtil.error(ResultEnum.Err_802));
                        //订单号重复
                        return ResultUtil.error(ResultEnum.Err_802);
                    }
                } catch (Exception e) {
                    StackTraceElement ste = e.getStackTrace()[0];
                    log.info("请求方式96:【{}】,机器号:【{}】,入库新增等待表的数据12:【{}】,异常的返回:【{}】,行号:【{}】", "充值请求", request.getMachNo(), entityXfRecordProcess, e, ste.getLineNumber());
                    log.info("请求方式97:【{}】,机器号:【{}】,请求参数:【{}】,返回:【{}】", "充值请求", request.getMachNo(), request, ResultUtil.error(ResultEnum.Err_802));
                    //订单号重复
                    return ResultUtil.error(ResultEnum.Err_802);
                }

                if (entityCardInfo != null) {
                    //修改卡流水
                    xfCardInfoService.upateCardMoneyA(request.getCompanyId(), entityCardInfo);
                }
                try {
                    EntityXfRecordProcess updateXfRecordProcess = new EntityXfRecordProcess();
                    updateXfRecordProcess.setPayState(1);
                    updateXfRecordProcess.setPayTime(new Date());
                    updateXfRecordProcess.setId(entityXfRecordProcess.getId());

                    entityXfRecordProcess.setPayState(1);
                    entityXfRecordProcess.setPayTime(updateXfRecordProcess.getPayTime());
                    entityXfRecordProcess.setId(null);
                    try {
                        xfAccountInfoService.updateAccountTransactional(request.getCompanyId(), entityXfAccountInfo.getId(), entityXfRecordProcess, updateXfRecordProcess);
                    } catch (Exception e) {
                        StackTraceElement ste = e.getStackTrace()[0];
                        log.info("请求方式98:【{}】,机器号:【{}】,修改金额的事务:【{}】,异常的返回:【{}】,行号:【{}】", "充值请求", request.getMachNo(), entityXfRecordProcess, e, ste.getLineNumber());
                    }

                    //支付成功
                    Map<String, Object> map = new HashMap<>();
                    map.put("discount", entityXfRecordProcess.getDiscount());
                    map.put("payAmount", Math.abs(entityXfRecordProcess.getRealMoney()));
                    Map<String, Object> mapAccountInf = new HashMap<>();
                    mapAccountInf.put("name", entityXfRecordProcess.getPName());
                    mapAccountInf.put("money", entityXfRecordProcess.getChargeBalance());
                    mapAccountInf.put("allowance", entityXfAccountInfo.getAccountSubsidyMoney());
                    if (entityCardInfo != null) {
                        mapAccountInf.put("expireDate", DateUtils.getStrDate(entityCardInfo.getEndDate(), DateUtils.YYYY_MM_DD_HH_MM_SS));
                    }
                    mapAccountInf.put("cardtype", entityXfAccountInfo.getAccTypeId());
                    map.put("accountInf", mapAccountInf);
                    return ResultUtil.success(map);
                } catch (Exception e) {
                    StackTraceElement ste = e.getStackTrace()[0];
                    log.info("请求方式99:【{}】,机器号:【{}】,入库新增等待表的数据13:【{}】,异常的返回:【{}】,行号:【{}】", "充值请求", request.getMachNo(), entityXfRecordProcess, e, ste.getLineNumber());
                    log.info("请求方式100:【{}】,机器号:【{}】,请求参数:【{}】,返回:【{}】", "充值请求", request.getMachNo(), request, ResultUtil.error(ResultEnum.Err_802));
                    //订单号重复
                    return ResultUtil.error(ResultEnum.Err_802);
                }
            } else {
                log.info("请求方式101:【{}】,机器号:【{}】,请求参数:【{}】,返回:【{}】", "充值请求", request.getMachNo(), request, ResultUtil.error(ResultEnum.Err_802));
                //订单号重复
                return ResultUtil.error(ResultEnum.Err_802);
            }
        } catch (Exception e) {
            StackTraceElement ste = e.getStackTrace()[0];
            log.info("请求方式102:【{}】,机器号:【{}】,请求参数:【{}】,异常:【{}】,行号:【{}】", "充值请求", request.getMachNo(), request, e, ste.getLineNumber());
            return ResultUtil.error(ResultEnum.Err_3031);
        }
    }

    /**
     * @return int
     * @author lu
     * @date 2021/5/26 15:38
     * @param:
     * @description 判断用什么码支付
     */
    private int payCode(String strCode) {
        if (strCode.equals("weixin")) {
            return 201;
        } else if (strCode.equals("alipay")) {
            return 202;
        } else if (strCode.equals("unionpay")) {
            return 203;
        } else if (strCode.equals("E-CNY")) {
            return 204;
        } else if (strCode.equals("ccbb")) {
            return 206;
        } else if (strCode.equals("icbc")) {
            return 207;
        } else if (strCode.equals("shebao")) {
            return 208;
        } else if (strCode.equals("zhongxin")) {
            return 313;
        }
        return 0;
    }


//	/**
//	 *   预下单接口(底层) (/preOrder)
//	 * */
//	@PostMapping(PayHandleUrl.URL_PreOrder)
//	public Result PreOrder(@Valid  @RequestBody PreOrderVo preOrderVo){
//		log.info("预下单接口请求参数:{{}}",preOrderVo);
//		//查找单位账号
//		List<EntityXfMerchantInfo> entityXfMerchantInfos = xfMerchantInfoService.selectComAcc(preOrderVo.getComId());
//
//		return ResultUtil.success();
//	}

    //线程池 多任务处理查询
//	@GetMapping("/ttt")
//	public Result testFeature(Long comId, Long pId){
//		ExecutorService executorService = new ThreadPoolExecutor(2, 2,
//				0, TimeUnit.SECONDS,
//				new ArrayBlockingQueue<>(512), // 使用有界队列，避免OOM
//				new ThreadPoolExecutor.DiscardPolicy());
//
//		Future<Object> future = executorService.submit(new Callable<Object>() {
//			@Override
//			public Object call() throws Exception {
//				EntityDeptInfo entityDeptInfo=deptInfoService.selectDeptName(1l,1l);
//				return entityDeptInfo;
////				throw new RuntimeException("exception in call~");// 该异常会在调用Future.get()时传递给调用者
//			}
//		});
//		Future<Object> future2 = executorService.submit(new Callable<Object>() {
//			@Override
//			public Object call() throws Exception {
//				EntityDeptInfo entityDeptInfo=deptInfoService.selectDeptName(1l,2l);
//				return entityDeptInfo;
////				throw new RuntimeException("exception in call~");// 该异常会在调用Future.get()时传递给调用者
//			}
//		});
//
//		try {
//			Object result1 = future.get();
//			Object result2 = future2.get();
//		} catch (InterruptedException e) {
//			// interrupt
//		} catch ( ExecutionException e) {
//			// exception in Callable.call()
//			e.printStackTrace();
//		}
//		return ResultUtil.success();
//	}


    //定时任务处理支付中的订单
    @GetMapping(PayHandleUrl.URL_paymentTiming)
    public void paymentTiming(@RequestParam("consState") Integer consState) {
        try {
            paymentTimings(1L, consState);
            log.info("定时任务处理支付中的订单:处理库一完成】");
            paymentTimings(600L, consState);
            log.info("定时任务处理支付中的订单:处理库二完成】");
        } catch (Exception e) {
            log.info("请求方式:【{}】,异常的返回:【{}】", "定时任务处理支付中的订单", e);
        }

    }

    //定时任务处理支付中的订单
    @GetMapping(PayHandleUrl.URL_ABCPaymentTimings)
    public void ABCPaymentTimings() {
        try {
            //农行缴费处理
            ABCPaymentTimings(1L, 10);
            log.info("定时任务处理农行缴费充值-支付中的订单:处理库一完成】");
            ABCPaymentTimings(600L, 10);
            log.info("定时任务处理农行缴费充值-支付中的订单:处理库二完成】");

        } catch (Exception e) {
            log.info("请求方式:【{}】,异常的返回:【{}】", "定时任务处理支付中的订单", e);
        }

    }

    private void paymentTimings(Long comId, Integer consState) throws Exception {

        Long minId = 0l;
        for (int k = 1; k < 100; k++) {
            //1、从待支付表中查询状态为支付中的消费记录（15分钟前、3天内）
            PageInfo<EntityXfRecordProcess> list = xfRecordProcessService.selectPayment(comId, consState, minId, k, 500);
            if (list.getList().size() == 0) {
                break;
            }
            for (EntityXfRecordProcess entityXfRecordProcess : list.getList()) {
            try {
                //查询配置信息
                EntiyXfMerchPayInfo entiyXfMerchPayInfo = configure(entityXfRecordProcess);
                if (entiyXfMerchPayInfo != null) {
                    //商户支付渠道未配置"
                    Map<String, Object> retMap = new HashMap<>();
                    retMap.put("company_id", entiyXfMerchPayInfo.getCompanyId());
                    retMap.put("user_name", entiyXfMerchPayInfo.getUserName());
                    retMap.put("password", entiyXfMerchPayInfo.getPassword());
                    retMap.put("pos_no", entityXfRecordProcess.getDeviceNo());
                    retMap.put("out_trade_no", entityXfRecordProcess.getOrderNo());
                    if(entityXfRecordProcess.getOrderNo().startsWith("CART")){
                        retMap.put("out_trade_no", entityXfRecordProcess.getPlatOrderNo());
                    }
                    //向统一支付平台发起支付
                    String payUrl = companyInfoService.getPayCenterUrl(entityXfRecordProcess.getComId(), entiyXfMerchPayInfo.getCompanyId());
                    String json = "";
                    if (entityXfRecordProcess.getPayWay() != null && entityXfRecordProcess.getPayWay() == 37 && entityXfRecordProcess.getOpTypeDiff() == 316l) {
                        json = HttpUtils.postsJson(payUrl + "/withholding/select.do", retMap);
                    } else {
                        json = HttpUtils.postsJson(payUrl + "/unifiedmicropay/select.do", retMap);
                    }
                    log.info("定时任务订单查询 vS17LoNL  页数【{}】单位【{}】 单号【{}】结果【{}】",k,entityXfRecordProcess.getComId(),entityXfRecordProcess.getOrderNo(),json);
                    JSONObject results = JSON.parseObject(json);

                    EntityXfRecordProcess updateXfRecordProcess = new EntityXfRecordProcess();
                    updateXfRecordProcess.setId(entityXfRecordProcess.getId());
                    updateXfRecordProcess.setPayChannelNo(entiyXfMerchPayInfo.getCompanyId());
                    updateXfRecordProcess.setComId(entityXfRecordProcess.getComId());
                    if (results.getInteger("code") == 200) {

                        if(entityXfRecordProcess.getOrderNo().startsWith("CART")){
                            //购物车处理逻辑
                            xfRecordProcessService.updateOrderPayState(entityXfRecordProcess.getComId(),entityXfRecordProcess.getPlatOrderNo());
                            continue;
                        }

                        Map<String, String> dataMap = (Map<String, String>) JSON.parse(results.getString("data"));
                        if (dataMap.get("trade_status").equals("SUCCESS")) {
                            //充值
                            if (consState == 10) {
                                ugcapiFeign.Check(entityXfRecordProcess.getComId(), entityXfRecordProcess.getOrderNo());
                                continue;
                            }
                            if (consState == 205 ) {
                                updateXfRecordProcess.setConsState(5);
                            }
                            updateXfRecordProcess.setChannelOrderNo(dataMap.get("trade_no"));
                            updateXfRecordProcess.setPayTime(DateUtil.getDate(dataMap.get("time_end"), "yyyyMMddHHmmss"));
                            updateXfRecordProcess.setPayWay(PayWar.getPayWar(dataMap.get("trade_type")));
                            updateXfRecordProcess.setPayState(1);
                            try {
                                int i = xfRecordProcessService.updateEntityXfRecord(updateXfRecordProcess.getComId(), updateXfRecordProcess);
                                if (i <= 0) {
                                    log.info("请求方式:【{}】,机器号:【{}】,入库修改的数据:【{}】,返回:【{}】", "定时任务处理支付中的订单", entityXfRecordProcess.getDeviceNo(), updateXfRecordProcess, "等待表修改入库失败");
                                    continue;
                                }
                            } catch (Exception e) {
                                log.info("请求方式:【{}】,机器号:【{}】,入库修改的数据:【{}】,异常的返回:【{}】", "定时任务处理支付中的订单", entityXfRecordProcess.getDeviceNo(), updateXfRecordProcess, e);
                            }
                            try {
                                MqSaveOrderVo mqSaveOrderVo = new MqSaveOrderVo();
                                mqSaveOrderVo.setComId(entityXfRecordProcess.getComId());
                                mqSaveOrderVo.setId(entityXfRecordProcess.getId());
                                mqSaveOrderVo.setMachNo(entityXfRecordProcess.getDeviceNo());
                                if (consState == 205 ) {
                                    mqSaveOrderVo.setType(3);
                                }
                                saveOrderProductService.saveOrder(JSON.toJSONString(mqSaveOrderVo));
                            } catch (Exception e) {
                                StackTraceElement ste = e.getStackTrace()[0];
                                log.info("请求方式:【{}】,机器号:【{}】定时任务-入库成功表数据的数据:【{}】,异常的返回:【{}】,行号:【{}】", "支付请求（定时任务处理）", entityXfRecordProcess.getDeviceNo(), entityXfRecordProcess, e, ste.getLineNumber());
                            }
                            //补缴处理
                            if (consState == 1 && !CommonUtil.isNull(entityXfRecordProcess.getOrigOrderNo())) {
                                entityXfRecordProcess.setPayTime(updateXfRecordProcess.getPayTime());
                                payFunService.waitPayRefund(entityXfRecordProcess);
                            }
                        }
                        if (dataMap.get("trade_status").equals("PAYERROR") ||
                                dataMap.get("trade_status").equals("REVOKED") || dataMap.get("trade_status").equals("CLOSED")
                                || dataMap.get("trade_status").equals("REFUND")) {
                            //支付失败
                            updateXfRecordProcess.setPayState(2);
                            if(results.getString("msg")!=null){
                                if(results.getString("msg").length()>49) results.put("msg",results.getString("msg").substring(0,45));
                                updateXfRecordProcess.setReserved2(results.getString("msg"));
                            }
                            try {
                                int i = xfRecordProcessService.updateEntityXfRecord(entityXfRecordProcess.getComId(), updateXfRecordProcess);
                                if (i <= 0) {
                                    log.info("请求方式:【{}】,订单号:【{}】,入库修改的数据:【{}】,返回:【{}】", "定时任务处理支付中的订单", entityXfRecordProcess.getOrderNo(), updateXfRecordProcess, "等待表修改入库失败");
                                    log.info("请求方式:【{}】,订单号:【{}】,统一支付平台的请求参数:【{}】,统一支付平台的返回:【{}】", "定时任务处理支付中的订单", entityXfRecordProcess.getOrderNo(), retMap, json);
                                }
                            } catch (Exception e) {
                                log.info("请求方式:【{}】,订单号:【{}】,入库修改的数据:【{}】,异常的返回:【{}】", "定时任务处理支付中的订单", entityXfRecordProcess.getOrderNo(), updateXfRecordProcess, e);
                                log.info("请求方式:【{}】,订单号:【{}】,统一支付平台的请求参数:【{}】,统一支付平台的返回:【{}】", "定时任务处理支付中的订单", entityXfRecordProcess.getOrderNo(), retMap, json);
                            }
                        }
                    } else if (results.getInteger("code") == 19 || results.getInteger("code") == 16) {
                        //支付结果未知
                    } else if (results.getInteger("code") == 21) {
                        //订单不存在
                        //支付失败
                        updateXfRecordProcess.setPayState(2);
                        if(results.getString("msg")!=null){
                            if(results.getString("msg").length()>49) results.put("msg",results.getString("msg").substring(0,45));
                            updateXfRecordProcess.setReserved2(results.getString("msg"));
                        }
                        try {
                            int i = xfRecordProcessService.updateEntityXfRecord(entityXfRecordProcess.getComId(), updateXfRecordProcess);
                            if (i <= 0) {
                                log.info("请求方式:【{}】,订单号:【{}】,入库修改的数据:【{}】,返回:【{}】", "定时任务处理支付中的订单", entityXfRecordProcess.getOrderNo(), updateXfRecordProcess, "等待表修改入库失败");
                                log.info("请求方式:【{}】,订单号:【{}】,统一支付平台的请求参数:【{}】,统一支付平台的返回:【{}】", "定时任务处理支付中的订单", entityXfRecordProcess.getOrderNo(), retMap, json);
                            }
                        } catch (Exception e) {
                            log.info("请求方式:【{}】,订单号:【{}】,入库修改的数据:【{}】,异常的返回:【{}】", "定时任务处理支付中的订单", entityXfRecordProcess.getOrderNo(), updateXfRecordProcess, e);
                            log.info("请求方式:【{}】,订单号:【{}】,统一支付平台的请求参数:【{}】,统一支付平台的返回:【{}】", "定时任务处理支付中的订单", entityXfRecordProcess.getOrderNo(), retMap, json);
                        }
                    } else {
                        log.info("请求方式:【{}】,订单号:【{}】,统一支付平台的请求参数:【{}】,统一支付平台的返回:【{}】", "定时任务处理支付中的订单", entityXfRecordProcess.getOrderNo(), retMap, json);
                    }
                    if(null!=updateXfRecordProcess.getPayState() && updateXfRecordProcess.getPayState()==2 && consState == 205){
                        try {
                            MqSaveOrderVo mqSaveOrderVo = new MqSaveOrderVo();
                            mqSaveOrderVo.setComId(entityXfRecordProcess.getComId());
                            mqSaveOrderVo.setId(entityXfRecordProcess.getId());
                            mqSaveOrderVo.setMachNo(entityXfRecordProcess.getDeviceNo());
                            mqSaveOrderVo.setType(3);
                            saveOrderProductService.saveOrder(JSON.toJSONString(mqSaveOrderVo));

                            xfGoodsListProcessService.xfGoodsListRrfund(entityXfRecordProcess.getComId(), entityXfRecordProcess.getOrderNo());
                        } catch (Exception e) {
                            StackTraceElement ste = e.getStackTrace()[0];
                            log.info("请求方式:【{}】,机器号:【{}】定时任务-入库成功表数据的数据:【{}】,异常的返回:【{}】,行号:【{}】", "支付请求（定时任务处理）", entityXfRecordProcess.getDeviceNo(), entityXfRecordProcess, e, ste.getLineNumber());
                        }
                    }

                } else {
                    log.info("请求方式:【{}】,订单号:【{}】,错误提示:【{}】", "定时任务处理支付中的订单", entityXfRecordProcess.getOrderNo(), "商户支付渠道未配置");
                }
            }catch (Exception exception){
                log.info("定时任务订单查询-异常 【{}】【{}】",entityXfRecordProcess.getOrderNo(),exception);
            }
        }}
    }

    //农行缴费处理支付中订单
    private void ABCPaymentTimings(Long comId, Integer consState) {
        try {
            List<EntityXfRecordProcess> list = xfRecordProcessService.selectPayment(comId, consState, 12l, ABCExposeEnum.QUERY_BILL.getValue());
            for (EntityXfRecordProcess entityXfRecordProcess : list) {
                //农行缴费平台
                try {
                    if (12l == entityXfRecordProcess.getOpType()) {
                        ABCConfirmTraceRequest request = new ABCConfirmTraceRequest();
                        request.setComId(entityXfRecordProcess.getComId());
                        request.setPId(entityXfRecordProcess.getPId().intValue());
                        request.setOrderNo(entityXfRecordProcess.getOrderNo());
                        request.setChannelOrderNo(entityXfRecordProcess.getChannelOrderNo());

                        log.info("请求方式:【{}】,订单号:【{}】,请求参数:【{}】", "定时任务处理支付中的农行缴费订单", entityXfRecordProcess.getOrderNo(), request);
                        exposeFeign.confirmTrace(request);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    log.info("定时任务处理支付中的农行缴费订单循环处理出现一次数据【{}】", entityXfRecordProcess);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
//	public static void  main(){
//		SignNoHandle signNoHandle =new SignNoHandle();
//		String signNo = signNoHandle.decrypt("SAJbHOR0nkKGbaze/BDV9rEIFE6U5erov26ss45WiJs=",1l);
//		System.out.println(	SignNoHandle signNoHandle =new SignNoHandle(););
//	}

    //主扫支付
    @PostMapping(PayHandleUrl.URL_PayHandle_staticCodePay)
    public Result staticCodePay(@RequestBody StaticCodePayRequest request) {
//        String data = JSON.toJSONString(request);
//        System.out.println(data);
        String machno = "";
        String tradeNo = "";
        try {
            machno = request.getMachNo();
            Long companyID = request.getCompanyId();
            //向redis分布式锁插入订单号是否重复
            //向redis分布式锁插入订单号是否重复
            tradeNo = request.getTradeNo();
            String tradeNoRedis = "staticCodePay:" + companyID + ":" + machno + ":" + tradeNo;
            if (redisUtil.lock(tradeNoRedis, 60 * 60)) {
                EntityXfRecordProcess entityXfRecordProcess = new EntityXfRecordProcess();
                entityXfRecordProcess.setOpType(24l);
                entityXfRecordProcess.setOpTypeDiff(201l);
                entityXfRecordProcess.setConsType(request.getConsType());
                entityXfRecordProcess.setOrderNo(request.getTradeNo());
                entityXfRecordProcess.setPlatOrderNo(request.getTradeNo());
                //判断消费时间段
                Date date = new Date();
                entityXfRecordProcess.setCreateTime(date);
                entityXfRecordProcess.setMonthValue(DateUtils.getStrDate(date, "yyyyMM"));
                //查询收费的和商家信息
                relatedDevice(entityXfRecordProcess, request.getCompanyId(), request.getMachNo(), date);
                entityXfRecordProcess.setMealDate(DateUtils.getDate(DateUtils.getStrDate(date, DateUtils.YYYY_MM_DD), DateUtils.YYYY_MM_DD));
                //计算金额
                int consMoney = -request.getAmount();
                entityXfRecordProcess.setConsMoney(Long.valueOf(consMoney));
                int discount = 0;
                int realMoney = consMoney + discount;
                //支付状态；0支付中、1支付成功，2支付失败，3撤单中，4已撤单，5退款中，6已退款，7部分退款成功
                entityXfRecordProcess.setPayState(0);
                entityXfRecordProcess.setDiscount(Long.valueOf(discount));
                entityXfRecordProcess.setRealMoney(Long.valueOf(realMoney));
                entityXfRecordProcess.setPayAmount(Long.valueOf(Math.abs(realMoney)));
                //消费状态，1：消费；2：退款；3：点餐；4.取餐；5.订餐；6：退订；10：充值；11：提现；12：补贴；13：清卡；21：销户
                entityXfRecordProcess.setConsState(1);
                entityXfRecordProcess.setOrderNo(request.getTradeNo());
                entityXfRecordProcess.setPayWay(request.getPayWay());
                try {
                    int i = xfRecordProcessService.insertEntityXfRecord(companyID, entityXfRecordProcess);
                    if (i <= 0) {
                        log.info("请求方式:【{}】,机器号:【{}】,请求参数:【{}】,返回:【{}】", "支付请求（强在线）", machno, request, ResultUtil.error(ResultEnum.Err_802));
                        //订单号重复
                        return ResultUtil.error(ResultEnum.Err_802);
                    }
                } catch (Exception e) {
                    StackTraceElement ste = e.getStackTrace()[0];
                    log.info("请求方式:【{}】,机器号:【{}】,入库新增等待表的数据14:【{}】,异常的返回:【{}】,行号:【{}】", "支付请求（强在线）", machno, entityXfRecordProcess, e, ste.getLineNumber());
                    log.info("请求方式:【{}】,机器号:【{}】,请求参数:【{}】,返回:【{}】", "支付请求（强在线）", machno, request, ResultUtil.error(ResultEnum.Err_802));
                    //订单号重复
                    return ResultUtil.error(ResultEnum.Err_802);
                }

                try {
                    if (request.getConsState() == 3 || request.getConsState() == 5) {
                        xfGoodsListProcessService.saveXfGoodsList(companyID, entityXfRecordProcess, request.getMealData());
                    }
                } catch (Exception e) {
                    StackTraceElement ste = e.getStackTrace()[0];
                    log.info("请求方式4:【{}】,机器号:【{}】,入库新增菜品缓存表数据的数据:【{}】,异常的返回:【{}】,行号:【{}】", "支付请求（强在线）", machno, entityXfRecordProcess, e, ste.getLineNumber());
                }
                //查询配置信息向统一平台发起支付
                EntiyXfMerchPayInfo entiyXfMerchPayInfo = configure(entityXfRecordProcess);
//				EntiyXfMerchPayInfo entiyXfMerchPayInfo=xfMerchPayInfoService.selectConfigure(request.getCompanyId(),0L);


                if (entiyXfMerchPayInfo == null) {
                    //商户支付渠道未配置"
                    return ResultUtil.error(ResultEnum.Err_3048);
                }

                EntityXfRecordProcess updateXfRecordProcess = new EntityXfRecordProcess();
                updateXfRecordProcess.setId(entityXfRecordProcess.getId());
                updateXfRecordProcess.setPayChannelNo(entiyXfMerchPayInfo.getCompanyId());
                try {
                    int i = xfRecordProcessService.updateEntityXfRecord(companyID, updateXfRecordProcess);
                    if (i <= 0) {
                        log.info("请求方式:【{}】,机器号:【{}】,入库修改的数据:【{}】,返回:【{}】", "支付请求（主扫）", machno, updateXfRecordProcess, "等待表修改入库失败");
                    }
                } catch (Exception e) {
                    StackTraceElement ste = e.getStackTrace()[0];
                    log.info("请求方式:【{}】,机器号:【{}】,入库修改的数据:【{}】,异常的返回:【{}】,行号:【{}】", "支付请求（主扫）", machno, updateXfRecordProcess, e, ste.getLineNumber());
                }

                //if opTypeDiff  == 201
                String payUrl = companyInfoService.getPayCenterUrl(request.getCompanyId(), entiyXfMerchPayInfo.getCompanyId());
                String RealUrl = payUrl + "/unifiedpreorder/lordesau.do";

                if (request.getType() == 1) {

                    Map<String, Object> stringObjectMap = new HashMap<>();
                    stringObjectMap.put("company_id", entiyXfMerchPayInfo.getCompanyId());
                    stringObjectMap.put("password", entiyXfMerchPayInfo.getPassword());
                    stringObjectMap.put("user_name", entiyXfMerchPayInfo.getUserName());

                    stringObjectMap.put("pos_no", request.getMachNo());
                    stringObjectMap.put("devsnip", "127.0.0.1");
                    stringObjectMap.put("out_trade_no", entityXfRecordProcess.getPlatOrderNo());
                    stringObjectMap.put("subject", entityXfRecordProcess.getDeptName() + "-" + request.getMachNo());
                    stringObjectMap.put("total_amount", request.getAmount());
                    stringObjectMap.put("fee_type", "CNY");
                    stringObjectMap.put("trade_type", "JSAPI");
                    stringObjectMap.put("payway", 3);
                    stringObjectMap.put("body", request.getCompanyId().toString());
                    stringObjectMap.put("operator", "admin");
                    stringObjectMap.put("openid", request.getOpenId());

                    RequestUtil requestUtil = new RequestUtil();

                    log.info("地址【{}】  参数【{}】", RealUrl, stringObjectMap);

                    Map<String, String> re = requestUtil.doPostJson(RealUrl, JSON.toJSONString(stringObjectMap));

                    Gson gson = new Gson();
                    Result result3 = gson.fromJson(gson.toJson(re), Result.class);

                    log.info("公众号返回【{}】  ", result3);

                    if (result3 == null || result3.getCode() != 200) {
                        return ResultUtil.info(result3.getCode(), result3.getMsg(), result3.getData());
                    }

                    JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(result3.getData()));
                    JSONObject jsonObject1 = JSON.parseObject(jsonObject.getString("prepay_id"));

                    Map<String, Object> map = new HashMap<>();
                    map.put("outTradeNo", jsonObject.getString("out_trade_no"));
                    map.put("timeStamp", jsonObject1.getString("timeStamp"));
                    map.put("nonceStr", jsonObject1.getString("nonce_str"));
                    map.put("appid", jsonObject1.getString("appid"));
                    map.put("sign", jsonObject1.getString("sign"));
                    map.put("mchId", jsonObject1.getString("mch_id"));
                    map.put("signType", jsonObject1.getString("signType"));

                    if (map.get("signType") == null) {
                        map.put("signType", "MD5");
                    }

                    map.put("subMchId", "");
                    if (!CommonUtil.isNull(jsonObject1.getString("sub_mch_id"))) {
                        map.put("subMchId", jsonObject1.getString("sub_mch_id"));
                    }
                    String prepayId = jsonObject1.getString("prepay_id");
                    if (CommonUtil.isNull(jsonObject1.getString("prepay_id"))) {
                        prepayId = jsonObject1.getString("package");
                    }
                    map.put("mchId", jsonObject1.getString("mch_id"));
                    if (prepayId != null && prepayId.startsWith("prepay_id=")) {
                        prepayId = prepayId.substring(10);
                    }
                    map.put("prepayId", prepayId);
                    map.put("type", 1);

                    return ResultUtil.success(map);

                }

                if (request.getType() == 8) {

                    Map<String,Object> stringObjectMap =new HashMap<>();
                    stringObjectMap.put("company_id", entiyXfMerchPayInfo.getCompanyId());
                    stringObjectMap.put("password", entiyXfMerchPayInfo.getPassword());
                    stringObjectMap.put("user_name", entiyXfMerchPayInfo.getUserName());


                    stringObjectMap.put("trade_type","SCAN");
                    stringObjectMap.put("pos_no","00000000");
                    stringObjectMap.put("devsnip","183.6.79.233");
                    stringObjectMap.put("out_trade_no", entityXfRecordProcess.getPlatOrderNo());
                    stringObjectMap.put("subject","建行扫码聚合支付");
                    stringObjectMap.put("total_amount", request.getAmount());
                    stringObjectMap.put("fee_type","CNY");

                    stringObjectMap.put("body", request.getCompanyId().toString());
                    stringObjectMap.put("operator","admin");

                    RequestUtil requestUtil=new RequestUtil();

                    log.info("地址【{}】  参数【{}】",RealUrl,stringObjectMap);

                    Map<String, String> re = requestUtil.doPostJson(RealUrl,JSON.toJSONString(stringObjectMap));

                    Gson gson = new Gson();
                    Result result3 = gson.fromJson(gson.toJson(re),Result.class);
                    if(result3.getCode()!=200){
                        return result3;
                    }

                    JSONObject  jsonObject = JSON.parseObject(JSON.toJSONString(result3.getData()));

                    Map<String, Object> map = new HashMap<>();
                    map.put("type",2);
                    map.put("code_url",jsonObject.get("code_url"));

                    log.info("建行聚合被扫返回【{}】  ",map);
                    return ResultUtil.success(map);
                }

                if(request.getType() == 26){
                    Map<String,Object> stringObjectMap =new HashMap<>();
                    stringObjectMap.put("company_id", entiyXfMerchPayInfo.getCompanyId());
                    stringObjectMap.put("password", entiyXfMerchPayInfo.getPassword());
                    stringObjectMap.put("user_name", entiyXfMerchPayInfo.getUserName());


                    stringObjectMap.put("trade_type","JSAPI");
                    stringObjectMap.put("pos_no","00000000");
                    stringObjectMap.put("devsnip","183.6.79.233");
                    stringObjectMap.put("out_trade_no", entityXfRecordProcess.getPlatOrderNo());
                    stringObjectMap.put("subject","农行支付");
                    stringObjectMap.put("pay_way",15);
                    stringObjectMap.put("total_amount", request.getAmount());
                    stringObjectMap.put("fee_type","CNY");

                    stringObjectMap.put("body", request.getCompanyId().toString());
                    stringObjectMap.put("operator","admin");

                    RequestUtil requestUtil=new RequestUtil();

                    log.info("地址【{}】  参数【{}】",RealUrl,stringObjectMap);

                    Map<String, String> re = requestUtil.doPostJson(RealUrl,JSON.toJSONString(stringObjectMap));

                    Gson gson = new Gson();
                    Result result3 = gson.fromJson(gson.toJson(re),Result.class);
                    if(result3.getCode()!=200){
                        return result3;
                    }

                    JSONObject  jsonObject = JSON.parseObject(JSON.toJSONString(result3.getData()));

                    Map<String, Object> map = new HashMap<>();
                    map.put("payTimeStamp",jsonObject.get("payTimeStamp"));
                    map.put("code_url",jsonObject.get("code_url"));
                    map.put("ordNo",jsonObject.get("ordNo"));

                    log.info("农行主扫返回【{}】  ",map);
                    return ResultUtil.success(map);
                }
                return ResultUtil.error(ResultEnum.Err_4112);

            } else {
                log.info("请求方式:【{}】,机器号:【{}】,请求参数:【{}】,返回:【{}】", "支付请求（主扫）", machno, request, ResultUtil.error(ResultEnum.Err_802));
                //订单号重复
                return ResultUtil.error(ResultEnum.Err_802);
            }
        } catch (Exception e) {
//            StackTraceElement ste = e.getStackTrace()[0];
//            log.info("请求方式:【{}】,机器号:【{}】,请求参数:【{}】,异常1:【{}】,行号:【{}】", "支付请求（主扫）", machno, request, e, ste.getLineNumber());
            log.error("请求方式:【{}】,机器号:【{}】,请求参数:【{}】,异常1:【{}】,行号:【{}】", "支付请求（主扫）", machno, request, e);
            return ResultUtil.error(ResultEnum.Err_3031);
        }
    }

    /**
     * 获取机器统一支付参数
     *
     * @param companyId
     * @param machNo
     * @return
     */
    @PostMapping(PayHandleUrl.URL_PayHandle_getUsefuleMerchPayInfo)
    public Result getUsefuleMerchPayInfo(Long companyId,
                                         @RequestParam(required = false, defaultValue = "") String machNo,
                                         @RequestParam(required = false, defaultValue = "1") Integer type) {
        EntiyXfMerchPayInfo entiyXfMerchPayInfo = null;
        if (type== 2) {
            //查询配置信息向统一平台发起支付
            EntityXfRecordProcess entityXfRecordProcess = new EntityXfRecordProcess();
            entityXfRecordProcess.setOrderNo("123");
         payHandleFunService.relatedDevice(entityXfRecordProcess,companyId,machNo,new Date());
            entiyXfMerchPayInfo = payHandleFunService.configure(entityXfRecordProcess);
        } else {
            entiyXfMerchPayInfo = xfMerchPayInfoService.selectConfigure(companyId, 0L);
        }
        if (entiyXfMerchPayInfo == null) {
            return ResultUtil.error(ResultEnum.Err_3053);
        }
        return ResultUtil.success(entiyXfMerchPayInfo);
    }

    /**
     * 2.5.6支付宝人脸机器初始化参数（getAlipayAuthInfo）
     */
    @PostMapping(PayHandleUrl.URL_PayHandle_getAlipayAuthInfo)
    public Result getAlipayAuthInfo(@RequestBody AlipayAuthInfoRequest request) {
        AlipayAuthInfoVo AlipayAuthInfoVo = null;
        if (StringUtils.isNotBlank(request.getMachNo())) {
            AuthinfoRequest authinfoRequest = new AuthinfoRequest();
            authinfoRequest.setMachNo(request.getMachNo());
            authinfoRequest.setCompanyId(request.getCompanyId());
            EntiyXfMerchPayInfo entiyXfMerchPayInfo = configureAuthinfo(authinfoRequest);
            if (entiyXfMerchPayInfo == null) {
                return ResultUtil.error(ResultEnum.Err_3053);
            }
            Map<String, Object> retMap = new HashMap<>();
            retMap.put("companyId", entiyXfMerchPayInfo.getCompanyId());
            retMap.put("userName", entiyXfMerchPayInfo.getUserName());
            retMap.put("password", entiyXfMerchPayInfo.getPassword());
            retMap.put("bizCode", "SCHOOL_PAYMENT");
            String payUrl = companyInfoService.getPayCenterUrl(request.getCompanyId(), entiyXfMerchPayInfo.getCompanyId());
            String json = HttpUtils.postsJson(payUrl + "/alischool/groupkeyQuery", retMap);
            JSONObject results = JSON.parseObject(json);
            if (results.getInteger("code") == 200) {
                AlipayAuthInfoVo = JSON.parseObject(results.getString("data"), AlipayAuthInfoVo.class);

            } else {
                return ResultUtil.error(ResultEnum.Err_4119);
            }

        }

        return ResultUtil.success(AlipayAuthInfoVo);
    }


    //支付宝离线
    @PostMapping(PayHandleUrl.URL_PayHandle_aliOfflinePay)
    public Result aliOfflinePay(@RequestBody TradeRecordRequest request) {

        try {

            String tradeNoRedis = "aliOfflinePay:" + request.getCompanyId() + ":" + request.getMachNo() + ":" + request.getTradeNo();

            if (!redisUtil.lock(tradeNoRedis, 3 * 60)) {
                log.info("请求方式:【{}】,机器号:【{}】,请求参数:【{}】,返回:【{}】", "支付宝刷脸支付请求（强在线）", request.getMachNo(), request, ResultUtil.error(ResultEnum.Err_802));
                //订单号重复
                return ResultUtil.error(ResultEnum.Err_802);
//				return ResultUtil.success();
            }
            //判断是什么支付类型
            //9 支付宝人脸
            EntityXfRecordProcess entityXfRecordProcess = new EntityXfRecordProcess();

            if (request.getUserId() == null) {
                request.setUserId(0l);
            }
            Long pId = request.getUserId();

            entityXfRecordProcess.setPId(pId);
            EntityPersonnelInfo entityPersonnelInfo = personnelInfoService.selectPersonnel(request.getCompanyId(), pId);
            EntityXfAccountInfo entityXfAccountInfo = xfAccountInfoService.selectAccountPid(request.getCompanyId(), pId);

            if (entityXfAccountInfo != null) {
                entityXfRecordProcess.setAccountNo(entityXfAccountInfo.getAccountNo());
//				entiyEntiyXfRecordProcess.setAccountNo(entityXfAccountInfo.getAccountNo());
            }

            if (entityPersonnelInfo != null) {
                entityXfRecordProcess.setPCode(entityPersonnelInfo.getPCode());
                entityXfRecordProcess.setPName(entityPersonnelInfo.getPName());
                //查询个人所在的组织
                entityXfRecordProcess.setDeptId(entityPersonnelInfo.getDeptId());
                if (entityPersonnelInfo.getDeptId() == null) {
                    entityPersonnelInfo.setDeptId(0l);
                }
                EntityDeptInfo entityDeptInfo = deptInfoService.selectDeptName(request.getCompanyId(), entityPersonnelInfo.getDeptId());
                if (entityDeptInfo != null) {
                    entityXfRecordProcess.setDeptName(entityDeptInfo.getDeptName());
                }
            }

            //9 微信人脸代扣 22人脸
            entityXfRecordProcess.setOpType(22l);
            entityXfRecordProcess.setOpTypeDiff(308l);

            entityXfRecordProcess.setComId(request.getCompanyId());
            entityXfRecordProcess.setDeviceNo(request.getMachNo());

            EntityCardInfo entityCardInfo = null;
            try {
                entityCardInfo = xfCardInfoService.selectCardByPid(request.getCompanyId(), pId);
                if (entityCardInfo != null) {
                    entityXfRecordProcess.setCardNo(entityCardInfo.getCardNo());
                } else {
                    entityXfRecordProcess.setCardNo(request.getUserId().toString());
                }
            } catch (Exception e) {
                log.info("离线记录-查卡号异常 【{}】", e);
            }

            entityXfRecordProcess.setPId(pId);

            //消费时间
            Date date = DateUtils.strToDate(request.getTradeTime());

            entityXfRecordProcess.setCreateTime(date);
            entityXfRecordProcess.setMonthValue(DateUtils.getStrDate(date, "yyyyMM"));
            //查询收费的和商家信息
            relatedDevice(entityXfRecordProcess, request.getCompanyId(), request.getMachNo(), date);

            entityXfRecordProcess.setMealDate(DateUtils.getDate(DateUtils.getStrDate(date, DateUtils.YYYY_MM_DD), DateUtils.YYYY_MM_DD));
            //消费状态，1：消费；2：退款；3：点餐；4.取餐；5.订餐；6：退订；10：充值；11：提现；12：补贴；13：清卡；21：销户
            entityXfRecordProcess.setConsState(1);
            entityXfRecordProcess.setOrderNo(request.getTradeNo());

            Integer intMealNo = 0;
            if (entityXfRecordProcess.getMealNo() != null) {
                intMealNo = Integer.valueOf(entityXfRecordProcess.getMealNo());
            }

            //判断扣款
            int consMoney = -1 * Math.abs(request.getAmount());
            int realMoney = consMoney;
            int discount = 0;
            //计算金额
            entityXfRecordProcess.setConsMoney(Long.valueOf(consMoney));

            if (entityPersonnelInfo != null && entityXfAccountInfo != null) {
                //计算优惠
                entityXfRecordProcess.setConsType(request.getConsType());
                discount = xfDiscountConfigServcie.selectSiscount(request.getCompanyId(), entityXfAccountInfo.getPId(),
                        entityXfAccountInfo.getAccTypeId(), request.getConsType(), date, intMealNo, request.getAmount(), entityXfRecordProcess);
                consMoney = entityXfRecordProcess.getConsMoney().intValue();
                realMoney = consMoney + discount;
            }

            //支付状态；0支付中、1支付成功，2支付失败，3撤单中，4已撤单，5退款中，6已退款，7部分退款成功
            entityXfRecordProcess.setPayState(0);
            entityXfRecordProcess.setDiscount(Long.valueOf(discount));
            entityXfRecordProcess.setRealMoney(Long.valueOf(realMoney));
            entityXfRecordProcess.setPayAmount(Long.valueOf(Math.abs(realMoney)));

            //避免空指针
            if (entityXfRecordProcess.getMealNo() == null) {
                entityXfRecordProcess.setMealNo("0");
            }


            int payState = 0;

            //第三方的支付失败结果
            JSONObject jsonObject = new JSONObject();
            //0不允许代扣  1代扣优先  2最后代扣

            //1代扣优先
            QrCardPayRequest qrCardPayRequest = new QrCardPayRequest();
            qrCardPayRequest.setCompanyId(request.getCompanyId());
            qrCardPayRequest.setTradeNo(request.getTradeNo());
            if (request.getUserId() != null) {
                qrCardPayRequest.setAuthCode(String.valueOf(request.getUserId()));
            }
            qrCardPayRequest.setType(9);
            qrCardPayRequest.setMachNo(request.getMachNo());
            qrCardPayRequest.setConsType(request.getConsType());

            qrCardPayRequest.setFaceToken(request.getFaceToken());
            qrCardPayRequest.setIotSignInfo(request.getVerificationData());
            qrCardPayRequest.setUId(request.getUId());
            qrCardPayRequest.setAmount(request.getAmount());

            payState = payFunService.withholding(entityXfRecordProcess, qrCardPayRequest, entityCardInfo, jsonObject);

            //插入缓存表失败
            if (payState == -11) {
                log.info("请求方式:【{}】,机器号:【{}】,请求参数:【{}】,返回:【{}】", "支付请求（支付宝离线-保存消费记录）", request.getMachNo(), request, ResultUtil.error(ResultEnum.Err_802));
                //订单号重复
                return ResultUtil.error(ResultEnum.Err_4002);
            }

            //成功
            if (payState == 1) {
                entityXfRecordProcess.setPayState(1);
            } else {
                entityXfRecordProcess.setPayState(0);
            }
            entityXfRecordProcess.setOpType(22l);

            if (payState == 1) {
                return ResultUtil.success();
            }

            if (entityPersonnelInfo == null || entityXfAccountInfo == null) {
                Result saveResult = xfRecordFeign.sveXfRecord(entityXfRecordProcess);
                log.info("离线消费-支付宝离线人脸支付-处理结果，【{}】【{}】【{}】【{}】【{}】【{}】【{}】", "支付宝代扣", "代扣成功或者无消费者", entityXfRecordProcess, entityPersonnelInfo, entityXfAccountInfo, request, saveResult);
                return ResultUtil.success();
            }

            //TODO
            try {

                EntityXfRecordProcess recordProcess = xfRecordProcessService.selectTradeNo(request.getCompanyId(), entityXfRecordProcess.getOrderNo(), request.getMachNo());

                EntityXfRecordProcess updateXfRecordProcess = new EntityXfRecordProcess();
                updateXfRecordProcess.setId(recordProcess.getId());
                updateXfRecordProcess.setPayState(1);
                updateXfRecordProcess.setPayTime(new Date());
                updateXfRecordProcess.setId(entityXfRecordProcess.getId());
                updateXfRecordProcess.setOpTypeDiff(100l);
                updateXfRecordProcess.setOpType(22l);

                Long chargeBalance = entityXfRecordProcess.getRealMoney() + entityXfAccountInfo.getAccountRechargeMoney();
                updateXfRecordProcess.setSubBalance(entityXfAccountInfo.getAccountSubsidyMoney());
                updateXfRecordProcess.setChargeBalance(chargeBalance);
                updateXfRecordProcess.setSubMoney(0L);
                updateXfRecordProcess.setChargeMoney(Long.valueOf(realMoney));

                updateXfRecordProcess.setPayState(1);

                entityXfRecordProcess.setSubMoney(updateXfRecordProcess.getSubMoney());
                entityXfRecordProcess.setChargeMoney(updateXfRecordProcess.getChargeMoney());
                entityXfRecordProcess.setSubBalance(entityXfAccountInfo.getAccountSubsidyMoney());
                entityXfRecordProcess.setChargeBalance(chargeBalance);
                entityXfRecordProcess.setOpType(22l);

                try {
                    xfAccountInfoService.updateAccountTransactional(request.getCompanyId(), entityXfAccountInfo.getId(), entityXfRecordProcess, updateXfRecordProcess);
                } catch (Exception e) {
                    StackTraceElement ste = e.getStackTrace()[0];
                    log.info("请求方式:【{}】,机器号:【{}】,修改金额的事务:【{}】,异常的返回:【{}】,行号:【{}】", "支付请求（保存消费记录）", request.getMachNo(), entityXfRecordProcess, e, ste.getLineNumber());
                }
            } catch (Exception e) {
                xfRecordFeign.sveXfRecord(entityXfRecordProcess);
                StackTraceElement ste = e.getStackTrace()[0];
                log.info("请求方式:【{}】,机器号:【{}】,入库新增等待表的数据15:【{}】,异常的返回:【{}】,行号:【{}】", "支付请求（支付宝离线）", request.getMachNo(), entityXfRecordProcess, e, ste.getLineNumber());
                log.info("请求方式:【{}】,机器号:【{}】,请求参数:【{}】,返回:【{}】", "支付请求（支付宝离线）", request.getMachNo(), request, ResultUtil.error(ResultEnum.Err_802));
            }
            return ResultUtil.success();

        } catch (Exception e) {
            StackTraceElement ste = e.getStackTrace()[0];
            log.info("请求方式:【{}】,机器号:【{}】,请求参数:【{}】,异常2:【{}】,行号:【{}】", "支付请求（强在线）", request.getMachNo(), request, e, ste.getLineNumber());
            return ResultUtil.error(ResultEnum.Err_3031);
        }
    }

    //2.4.11 代扣补缴（backPay）
    @PostMapping(PayHandleUrl.URL_PayHandle_backPay)
    public Result backPay(@RequestBody BackPayRequest request) {
        log.info("请求方式bj1:【{}】,机器号:【{}】,请求参数:【{}】", "代扣补缴", request.getBackId(), request);
        try {

            String tradeNoRedis = "backPay:" + request.getCompanyId() + ":" + request.getBackId() + ":" + request.getTradeNo();

            if (!redisUtil.lock(tradeNoRedis, 3 * 60)) {
                log.info("请求方式:【{}】,机器号:【{}】,请求参数:【{}】,返回:【{}】", "代扣补缴", request.getBackId(), request, ResultUtil.error(ResultEnum.Err_802));
                //订单号重复
                return ResultUtil.error(ResultEnum.Err_802);
            }

            EntityXfRecordWaitpay entityXfRecordWaitpay2 = xfRecordWaitpayService.getXfRecordWaitpayInfo(request.getCompanyId(),request.getBackId());

            if(entityXfRecordWaitpay2.getPayState() == 1){
                Map<String, Object> mapResult = new HashMap<>();
                mapResult.put("discount", entityXfRecordWaitpay2.getDiscount());
                mapResult.put("payAmount",Math.abs(entityXfRecordWaitpay2.getPayAmount()));
                Map<String, Object> mapAccountInf = new HashMap<>();
                mapAccountInf.put("name", entityXfRecordWaitpay2.getPName());
                mapAccountInf.put("money", entityXfRecordWaitpay2.getChargeBalance());
                mapAccountInf.put("allowance", entityXfRecordWaitpay2.getSubBalance());
                mapAccountInf.put("cardtype", 0);
                mapResult.put("accountInf", mapAccountInf);
                mapResult.put("pickupNum", "0");
                mapResult.put("orderTime", new Date());
                mapResult.put("repairList", new ArrayList<>());
                return ResultUtil.success(mapResult);
            }

            if(entityXfRecordWaitpay2.getPayState() == 0){
                log.info("请求方式bj2:【{}】,机器号:【{}】,请求参数:【{}】,返回:【{}】", "代扣补缴", request.getBackId(),request, entityXfRecordWaitpay2);
                return ResultUtil.error(ResultEnum.Err_2043);
            }

            //判断是什么支付类型
            //9 支付宝人脸
            EntityXfRecordProcess entityXfRecordProcess = JSON.parseObject(JSON.toJSONString(entityXfRecordWaitpay2),EntityXfRecordProcess.class);
            entityXfRecordProcess.setDeptName("发起补缴:"+request.getMachNo());

            Long pId = entityXfRecordWaitpay2.getPId();

            entityXfRecordProcess.setPId(pId);
            EntityPersonnelInfo entityPersonnelInfo = personnelInfoService.selectPersonnel(request.getCompanyId(), pId);
            EntityXfAccountInfo entityXfAccountInfo = xfAccountInfoService.selectAccountPid(request.getCompanyId(), pId);

            if (entityXfAccountInfo == null) {
                return ResultUtil.error(ResultEnum.Err_1001);
            }
            entityXfRecordProcess.setAccountNo(entityXfAccountInfo.getAccountNo());

            if (entityPersonnelInfo == null || 0 != entityPersonnelInfo.getStatus()) {
                return ResultUtil.error(ResultEnum.Err_4022);
            }

            //9 微信人脸代扣 22人脸
            entityXfRecordProcess.setOpType(1l);
            entityXfRecordProcess.setOpTypeDiff(306l);
            entityXfRecordProcess.setCreateTime(new Date());
            entityXfRecordProcess.setMonthValue(DateUtils.getStrDate(new Date(), "yyyyMM"));

            //消费状态，1：消费；2：退款；3：点餐；4.取餐；5.订餐；6：退订；10：充值；11：提现；12：补贴；13：清卡；21：销户
            entityXfRecordProcess.setConsState(1);
            entityXfRecordProcess.setOrderNo(request.getTradeNo());
            entityXfRecordProcess.setPlatOrderNo(entityXfRecordWaitpay2.getOrderNo());

            //判断扣款
            int consMoney = -1 * Math.abs(entityXfRecordWaitpay2.getConsMoney().intValue());
            int realMoney = consMoney;
            int discount = 0;
            //计算金额
            entityXfRecordProcess.setConsMoney(Long.valueOf(consMoney));

            if (entityPersonnelInfo != null && entityXfAccountInfo != null) {
                //计算优惠
                entityXfRecordProcess.setConsType(entityXfRecordProcess.getConsType());
                discount = xfDiscountConfigServcie.selectSiscount(request.getCompanyId(), entityXfAccountInfo.getPId(),
                        entityXfAccountInfo.getAccTypeId(), entityXfRecordProcess.getConsType(), entityXfRecordProcess.getConsTime(), Integer.valueOf(entityXfRecordProcess.getMealNo()), Math.abs(entityXfRecordProcess.getPayAmount().intValue()), entityXfRecordProcess);
                consMoney = entityXfRecordProcess.getConsMoney().intValue();
                realMoney = consMoney + discount;
            }

            //支付状态；0支付中、1支付成功，2支付失败，3撤单中，4已撤单，5退款中，6已退款，7部分退款成功
            entityXfRecordProcess.setPayState(0);
            entityXfRecordProcess.setDiscount(Long.valueOf(discount));
            entityXfRecordProcess.setRealMoney(Long.valueOf(realMoney));
            entityXfRecordProcess.setPayAmount(Long.valueOf(Math.abs(realMoney)));

            //避免空指针
            if (entityXfRecordProcess.getMealNo() == null) {
                entityXfRecordProcess.setMealNo("0");
            }

            int payState = 0;

            //第三方的支付失败结果
            JSONObject jsonObject = new JSONObject();
            //0不允许代扣  1代扣优先  2最后代扣

            //1代扣优先
            QrCardPayRequest qrCardPayRequest = new QrCardPayRequest();
            qrCardPayRequest.setCompanyId(request.getCompanyId());
            qrCardPayRequest.setTradeNo(request.getTradeNo());
            qrCardPayRequest.setAuthCode(entityXfRecordProcess.getPId().toString());
            qrCardPayRequest.setType(1);
            qrCardPayRequest.setMachNo(entityXfRecordProcess.getDeviceNo());
            qrCardPayRequest.setConsType(entityXfRecordProcess.getConsType());
            qrCardPayRequest.setAmount(Math.abs(entityXfRecordProcess.getPayAmount().intValue()));
            payState = payFunService.withholding(entityXfRecordProcess, qrCardPayRequest, null, jsonObject);

            log.info("【公众号补缴结果】【{}】，【{}】", payState, qrCardPayRequest);

            EntityXfRecordWaitpay entityXfRecordWaitpay = new EntityXfRecordWaitpay();
            entityXfRecordWaitpay.setId(entityXfRecordWaitpay2.getId());
            entityXfRecordWaitpay.setPlatOrderNo(entityXfRecordProcess.getOrderNo());
            //成功
            if (1 == payState) {
                EntityXfRecordProcess recordProcess = xfRecordProcessService.selectTradeNo(request.getCompanyId(), entityXfRecordProcess.getOrderNo(), null);
                entityXfRecordWaitpay.setPayTime(recordProcess.getPayTime());
                entityXfRecordWaitpay.setPayState(recordProcess.getPayState());
                entityXfRecordWaitpay.setDiscount(recordProcess.getDiscount());
                entityXfRecordWaitpay.setRealMoney(recordProcess.getRealMoney());

//                Result result = payConfigClientService.updatePayState(entityXfRecordWaitpay);

                boolean up = xfRecordWaitpayService.updateXfRecordWaitpayById(request.getCompanyId(),entityXfRecordWaitpay);

                log.info("公众号补缴，更新待补缴记录为成功【{}】，【{}】", up, entityXfRecordWaitpay);
                //成功
                Map<String, Object> mapResult = new HashMap<>();
                mapResult.put("discount", entityXfRecordProcess.getDiscount());
                mapResult.put("payAmount",Math.abs(entityXfRecordProcess.getPayAmount()));
                Map<String, Object> mapAccountInf = new HashMap<>();
                mapAccountInf.put("name", entityXfRecordProcess.getPName());
                mapAccountInf.put("money", entityXfAccountInfo.getAccountRechargeMoney());
                mapAccountInf.put("allowance", entityXfAccountInfo.getAccountSubsidyMoney());
                mapAccountInf.put("cardtype", 0);
                mapResult.put("accountInf", mapAccountInf);
                mapResult.put("pickupNum", "0");
                mapResult.put("orderTime", new Date());
                mapResult.put("repairList", new ArrayList<>());
                return ResultUtil.success(mapResult);
            } else if (2 == payState || -1 == payState || -2 == payState) {
                entityXfRecordWaitpay.setPayState(-1);
                boolean up = xfRecordWaitpayService.updateXfRecordWaitpayById(request.getCompanyId(),entityXfRecordWaitpay);
//                Result result = payConfigClientService.updatePayState(entityXfRecordWaitpay);
                log.info("公众号补缴 I35U9cG1  ，更新待补缴记录为失败【{}】代扣返回【{}】【{}】，【{}】", request.getCompanyId(),jsonObject,up, entityXfRecordWaitpay);
                return ResultUtil.info(3030, jsonObject.getString("msg"));
            } else {
                entityXfRecordWaitpay.setPayState(0);
                boolean up = xfRecordWaitpayService.updateXfRecordWaitpayById(request.getCompanyId(),entityXfRecordWaitpay);
                log.info("公众号补缴，更新待补缴记录为支付中【{}】【{}】，【{}】",request.getCompanyId(), up, entityXfRecordWaitpay);
                //支付结果未知
                return ResultUtil.error(ResultEnum.Err_3029);
            }
        } catch (Exception e) {
            StackTraceElement ste = e.getStackTrace()[0];
            log.info("请求方式:【{}】,机器号:【{}】,请求参数:【{}】,异常2:【{}】,行号:【{}】", "公众号补缴", request.getBackId(), request, e, ste.getLineNumber());
            return ResultUtil.error(ResultEnum.Err_3031);
        }
    }



}


